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 understand the multi-thread in c #

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

Share

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

This article introduces the relevant knowledge of "how to understand multithreading in c #". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

I. introduction

II. Lock

III. Monitor

IV. Interlocked

5. Semaphore

VI. Event

7. Barrier

VIII. ReaderWriterLockSlim

IX. Mutex

ThreadLocal, AsyncLocal,Volatile

11. Interesting examples

Summary

I. introduction

First give a definition of the Num class

Internal class Num {public static int odd = 50000; public static int even = 10,000;}

Assuming that you are now required to output all odd numbers less than odd and all even numbers less than even, you can write the following code without considering multithreading: (in order to demonstrate the contention between threads in multithreading, first assign the value to num, in fact, this assignment operation is meaningless.)

/ / synchronize code snippet public long Sum () {Stopwatch sw = new Stopwatch (); sw.Start (); int num = 0; for (int I = 0; i new LockFor (). Sum ()); var T3 = new TaskFactory (). StartNew () = > new LockFor (). Sum (); Task.WaitAll (T1, T2, T3); sw.Stop (); Console.WriteLine (sw.ElapsedMilliseconds); sw.Restart () Var T4 = new TaskFactory (). StartNew () = > new LockForStaticSync (). Sum (); var T5 = new TaskFactory (). StartNew () = > new LockForStaticSync (). Sum (); var T6 = new TaskFactory (). StartNew () = > new LockForStaticSync (). Sum (); Task.WaitAll (T4, T5, T6); sw.Stop (); Console.WriteLine (sw.ElapsedMilliseconds);}

But the actual execution result is unexpected, after many runs, the class variable lock runs much faster than the object variable, why?

After thinking about it, considering that the class variable omits the time it takes to create a locked object each time, and a small number of loops may not make up for this time gap, I gradually scale up the variables defined in the Num class. With the increase of the number of loops, that is, the increase of method execution time, the advantage of object variables gradually becomes apparent.

Since object variables have the advantage of speed, and multi-party calls are inevitable in the process of use, should they always be defined as object variables? In fact, this is not the case, for example, the locking objects needed in static classes, global cache dictionaries, and file operation help classes should all be static locks. More scenarios are welcome to add.

IV. Interlocked

The methods in the Interlocked class can achieve atomic operations, through the operating system and hardware CPU-level control to ensure that CPU will not be interrupted when performing the current operation. This class provides some simple methods, such as Add,Increment and so on.

5. Semaphore

A semaphore is a counting mutex lock. What do you mean? In the case of Monitor, from monitor.enetr to monitor.exit, the wrapped code can only be accessed by one thread at a time, while Semaphore can define the number of threads accessing certain resources at the same time, that is, allowing multiple threads to access protected code at the same time.

Semaphore has three signed constructors, where the parameters of Semaphore (int initialCount, int maximumCount) specify the number and maximum number of semaphores that are initially released, and the difference between them belongs to the thread that created the semaphore.

The following is from MSDN

Class SemaphoreTest {/ / A semaphore that simulates a limited resource pool. Private static Semaphore _ pool; / / assists in setting thread sleep time. Private static int _ padding; public static void Main () {/ / here is a semaphore that can have up to three access threads, but it can be used as 0 at this time and will not be available until the current thread is released. / / if the available amount is not set here, 3 is still passed when the main thread is released, and the exception of SemaphoreFullException _ pool = new Semaphore (0,3); for (int I = 1; I PrintEven (even,odd)); var tb = Task.Run (() = > PrintOdd (even,odd)) will occur during the running of the program } / / wait for your own signal to control the signal of another thread public void PrintEven (EventWaitHandle evenHandle, EventWaitHandle oddHandle) {string design = "even"; for (int I = 0; I)

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