当前位置:网站首页>[C.NET] 11: the most basic thread knowledge

[C.NET] 11: the most basic thread knowledge

2020-11-10 09:12:00 Exquisite Manor

There's too much knowledge about threads , There are deep and shallow knowledge , Further research will involve operating systems 、CUP、 Memory , In a nutshell, it's just some grammar . There is no certain accumulation of knowledge , It's hard to write a comprehensive knowledge of threads , Of course, I don't have the ability . So think of a point and write a point , Try to summarize some useful knowledge points . Thread is a big story , This series may be about threads several times , Start with the basics , Warm up .

Some basic concepts

Threads (Thread) It is the smallest unit that the operating system can schedule operations . It's the actual unit of operation in the process , A process can be concurrent with multiple Threads , Every one of them Threads Perform different tasks in parallel . Strictly speaking , The number of threads that can run concurrently at the same time depends on CPU The number of nuclear .

According to the thread running mode , Threads can be divided into foreground threads 、 Background threads and daemons (Deamon) Threads :

  • Foreground Threads : The main program must wait for the thread to execute before it can exit the program .C# Medium Thread The default is foreground thread , It can also be set as background thread .

  • Background thread : After the main program is executed, it will exit immediately , Whether the thread is finished or not .C# Of ThreadPool The managed thread is the background thread by default .

  • The guardian thread : The guardian thread has the feature of automatically ending its own life cycle , It's usually used to perform some background tasks .

Each time a new thread is opened, it consumes a certain amount of memory , Even if the thread does nothing , It will at least consume 1M Left and right memory .

Multithreading parallel (Parallelism) and Concurrent (Concurrency) The difference between :

  • parallel : At the same time There are multiple instructions on multiple processors meanwhile perform , Both macro and micro are happening at the same time .
  • Concurrent : It means in In the same period of time , Macroscopically, multiple instructions seem to be executed at the same time , Microscopically, it is the fast switching execution of multiple instruction processes , Only one instruction may be executed at the same time .

PS: The above concept comes from Google Multiple search results for , Sort it out a little bit .

Thread、ThreadPool and Task

Yes C# For developers , You can't help but understand Thread、ThreadPool and Task These three concepts . This is also a topic with high interview frequency , stay StackOverflow You can find a lot of good answers , I summed it up .

Thread

Thread It's an actual operating system level thread (OS Threads ), It has its own stack and kernel resources .Thread Allow the highest degree of control , You can Abort、Suspend or Resume One thread , You can also monitor its status , Set its stack size and Culture Equal attribute .Thread The cost of spending is very high , Each of your threads consumes relatively more memory for its stack , In addition, when the processor context switches between threads, additional CPU expenses .

ThreadPool

ThreadPool( Thread pool ) It's a wrapper for a bunch of threads , from CLR maintain . You have no control over the threads in the thread pool , You don't even know when the thread pool will start executing your submitted tasks , You can only control the size of the thread pool . Simply speaking , The mechanism of thread pool calling thread is , It first calls the created idle thread to perform your task , If there are currently no idle threads , New threads may be created , It may also wait .

Use ThreadPool You can avoid the overhead of creating too many threads . however , If you go to ThreadPool Submitted tasks that run too long , It may be filled with , At this point, the later tasks you submit may eventually wait for the previous long-running tasks to be completed . Besides , The thread pool does not provide any way to detect when a work task is completed ( Unlike Thread.Join()), There's no way to get results . therefore ,ThreadPool It is best used for short-term operations where the caller does not need the result .

Task

Task yes TPL(Task Parallel Library) Provide a class , It's in Thread and TheadPool Provides the best of both worlds solution . and ThreadPool equally ,Task Don't create your own OS Threads . contrary ,Task By TaskScheduler The scheduler performs , The default scheduler is only in ThreadPool Up operation .

And ThreadPool The difference is ,Task It also allows you to know when it's finished , And get and return a result . You can use the existing Task On the call ContinueWith(), Make it run more code after the task is finished ( If it's done , It will immediately run the callback ).

You can also call Wait() To synchronously wait for a task to complete ( perhaps , By getting it Result attribute ). And Thread.Join() equally , This blocks the calling thread , Until the job is done. . It is generally not recommended to wait for the task to complete , It prevents the calling thread from doing anything else . If the current thread is waiting for other threads to complete their tasks , It is recommended to use async/await Asynchronous waiting , In this way, the current thread can be idle to deal with other tasks , For example await Task.Delay() when , It doesn't take up thread resources .

Because the mission is still ThreadPool Up operation , Therefore, it should not be used for the execution of long-term tasks , Because they fill the thread pool and block new work tasks . contrary ,Task Provides a LongRunning Options , It will tell TaskScheduler Enable a new thread , Not in ThreadPool Up operation .

All the newer upper level multithreading API, Include Parallel.ForEach()、PLINQ、async/await etc. , It's all based on Task Upper .

Thread and Task A simple example

Here's a simple example to demonstrate Thread and Task Use , Notice how they create 、 The ginseng 、 Executing and waiting for execution to complete .

static void Main(string[] args)
{
    //  Create two new  Thread
    var thread1 = new Thread(new ThreadStart(() => PerformAction("Thread", 1)));
    var thread2 = new Thread(new ThreadStart(() => PerformAction("Thread", 2)));

    //  Start executing thread tasks 
    thread1.Start();
    thread2.Start();

    //  Wait for two threads to execute 
    thread1.Join();
    thread1.Join();

    Console.WriteLine("Theads done!");

    Console.WriteLine("=== I'm the divider ===");

    //  Create two new  Task
    var task1 = Task.Run(() => PerformAction("Task", 1));
    var task2 = Task.Run(() => PerformAction("Task", 2));

    //  Execute and wait for two  Task  Execution completed 
    Task.WaitAll(new[] { task1, task2 });

    Console.WriteLine("Tasks done!");

    Console.ReadKey();
}

static void PerformAction(string threadOrTask, int id)
{
    var rnd = new Random(id);
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine($"{threadOrTask}: {id}: {i}", id, i);
        Thread.Sleep(rnd.Next(0, 1000));
    }
}

Running effect :

be aware , by comparison Task Than Thread Much easier to use , Add the above Task and Thread Comparison of , The guiding significance of our coding is : Most of the time we should use Task, Don't use it directly Thread, Unless you know clearly that you need a separate thread to perform a long, time-consuming task .

Summary

This article is very basic , Tidy up C# Important concepts related to thread programming , A simple demonstration of Thread and Task Use .Thread and Task It's a high-frequency interview topic , In especial Thread and Task The difference between ,Thread Lower level ,Task More abstract , The key to answering these questions is ThreadPool.

版权声明
本文为[Exquisite Manor]所创,转载请带上原文链接,感谢