Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement CSP concurrency Model in C #

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to realize CSP concurrency model in C #". In daily operation, I believe many people have doubts about how to realize CSP concurrency model in C #. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to realize CSP concurrency model in C #". Next, please follow the editor to study!

CSP (Communicating sequential processes)

At first, I thought it was very simple, but later, I found that it was unique. I was a language and a set of theories. Here I do not in-depth to do too much insight into it, I am afraid to delay you = _ =, you can take a look at wiki.

Wiki: https://en.wikipedia.org/wiki/Communicating_sequential_processes

Let's do some analysis of it from the perspective of Go and extract a summary:

"used to describe a concurrency model in which two independent concurrent entities communicate through a shared communication channel. Channel is the first type of object in CSP, which focuses not on the entity sending the message, but on the channel used to send the message."

Well, CSP is written separately to let you know that this is a language-independent set of things. If you are interested, you can check out wiki and search some other materials.

CSP in Go

Channel (Channel)

Goroutine (do not know how to translate, you can understand as a "worker", not a worker thread. The essence is to realize the cooperative process. )

Collaborative process (a sharp weapon to improve concurrency)

Everyone knows exactly what a thread can do, but what is a collaborative process? How does it compare to threads?

Thread

Let's rethink something.

CPU: core, hyperthreading

OS: thread

Programming language: thread pool

I won't go into details here, but just click on it.

Any calculation we do has to be calculated by CPU, and the number of kernels of CPU directly determines how many things we can do for CPU.

There is a poll inside the OS that we commonly use today, which allocates any calculation in the form of a time slice that takes turns using CPU to perform calculations, and threads are the carriers of these tasks.

The concept of this piece is very large (and involves, what is concurrency, what is parallel). This is not the focus of this article. If you are interested, you can open a separate article to explain the content of this piece.

Coming back to this article, we now know that threading is a technical implementation at the operating system level to share CPU. Multithreaded programming has blossomed in all major languages.

So why do you need to cooperate?

Thread overhead

This is another big knowledge point, and there are no more introductions here.

We just need to understand that threads are not cheap, and that the creation of a thread has at least two points of overhead.

Memory

Scheduler pressure (thread context switching, etc.)

Threads can hold logical data (for example, HttpContext.Current, objects, etc.), so they must occupy memory (as for how much memory is used, different languages are different from OS)

If a CPU is 4 cores and can only handle 4 tasks at the same time, the more threads in an OS, the longer it will take them to train a whole circle. Each time you schedule a thread, you need to copy the state of the current thread context, and then read the state that is ready to schedule the thread context.

You can see the last point here that sometimes multithreading is slower than single threading, so multithreading performance improvement is essentially fake. Multithreading does not improve program performance.

I know there must be people here who have doubts. Most people say that multithreading is used to improve performance. Why is multithreading slower than single thread?

Let's think about this: PHP and NodeJS,PHP do not support multithreading by default. NodeJS uses single-threaded event polling. Are they less efficient than languages with multithreading? Not really.

The reason why multithreading is fast is because of cheating. If you ask two people to do what others do alone, it will certainly be faster than single threading. This is also very limited, multi-threaded execution of things to avoid sharing as much as possible, otherwise you may not be as efficient as single-threaded.

What is said here is a bit beside the point, the content of this piece is really too big, as long as we know that threads are by no means cheap even if they are not expensive.

To solve this problem, all major languages have introduced a technology called thread pool. I apply for a group of threads, hold them, and use them directly when there is a task, so that I don't create and destroy threads frequently. This greatly improves the efficiency.

In .NET, it has long been advocated to use ThreadPool whenever a thread is needed.

Ps: in most languages (runtime) that I haven't seen yet, threads correspond to operating system threads one by one.

Regression cooperation process

There is a many-to-one relationship between a co-program and a thread, and multiple co-programs correspond to a single thread. It has the same relationship as threads and CPU.

Threads are designed to share CPU, while collaborators are designed to share threads.

The collaborative process is the implementation of its own "thread" at the application level. In other words, we build a set of "threading" system without changing the thread logic of OS.

Why not directly change the OS thread to make it lighter? Personally, I think 1 is a matter of historical compatibility, 2 is a matter of necessity, and threads are a good abstract logic. The implementation of the collaboration process can be completed through threads.

The purpose of the cooperation process

Let's think about a scene.

Grab the html of Baidu, google and bing.

The practice of multithreading is

Start three threads to initiate HTTP GET requests for Baidu, google and bing respectively. Three threads are used at this time.

The way to cooperate is (extreme)

Start a thread to initiate a HTTP GET request to Baidu, put the task in the queue, issue the HTTP GET request to the google, put the task in the queue, and put the task in the queue to the bingHTTP GET request.

At this point, only one thread is required (in extreme cases, most implementations need at least two threads, because a background thread is required to listen on the task queue, and then assign an available thread to handle the following logic when the task is completed)

Why in extreme cases? Because the cooperative process may sometimes correspond to the thread one by one, for example, your CPU has eight cores, and running four cores at the same time may assign four threads to handle these four tasks separately, which mainly depends on the scheduling algorithm.

Summary: the purpose of collaboration is to improve thread utilization and reduce the useless work of threads (mostly IO congestion), and it is also more suitable for IO-intensive scenarios.

The Cooperative Program in C #

As you can see, the three tasks are executed asynchronously, but all are handled by thread 4, which means that only one thread is used for the three asynchronous tasks.

CSP in C #

After talking about such a long journey, I finally returned to today's topic.

In fact, just to implement CSP, there is no need to sort out threads and co-programs at all. But today's main comparison is the CSP in Go, so it is basically meaningless without a collaborative program.

How does C # correspond to the most important Channel in CSP?

The answer is: BlockingCollection

Let's look at an example.

Grab a batch of websites and output the title of the site

The code logic for initiating a HTTP GET request and parsing Title is as follows:

The code of the main program is as follows

Execution logic

Enable a producer co-program to produce the corresponding html according to url while using the main thread to consume the contents of the queue (asynchronously)

Each url sets up a separate cooperative process to initiate HTTP GET requests.

The producer cooperates to wait for all the html of url to be loaded

Mark queue completion

Main thread exits

The implementation results are as follows:

What is the difference between Go and. Net?

Getting rid of some of the logic in the implementation is essentially not much different.

But one of the inherent advantages of Go is that it is the language of a new era, abandoning threads. In other words, there is no threading at the Go level, it only has a co-program.

But threads in .NET have been available for many years, and a large number of class libraries and drivers are done using threads.

So even if you use a co-program in the upper layer, there may not be only one thread to complete the execution at the bottom, and you can create your own thread to run the logic at the bottom. Later, we will introduce the content of this piece.

At this point, the study on "how to implement the CSP concurrency model in C #" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report