Multithreaded programming has a unique problem with respect to single threading, which is a thread-safe issue. The so-called thread safety is that if your code is in a process where multiple threads are running concurrently, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected. Thread safety issues are caused by global variables and static variables.
In order to ensure the security of access static variables in multi-threaded situations, the lock mechanism can be used to ensure that:
1 //static global variables that require locking2 Private Static BOOL_isok =false;3 //Lock can only lock one reference type variable4 Private Static Object_lock =New Object();5 Static voidMLock ()6 {7 //Multithreading8 NewSystem.Threading.Thread (done). Start ();9 NewSystem.Threading.Thread (done). Start ();Ten console.readline (); One } A - Static voidDone () - { the //Lock can only lock one reference type variable - Lock(_lock) - { - if(!_isok) + { -Console.WriteLine ("OK"); +_isok =true; A } at } -}
It is important to note that lock can only lock an object of a reference type. In addition, in addition to the locking mechanism, the async and await methods are included in the high version of C # to ensure thread safety, as follows:
1PublicStaticClassAsynandawait2{3//Step 14PrivateStaticint count =0;5//Use async and await to guarantee static variable count security in multi-thread6PublicAsyncStaticvoidM1 ()7{8//Async and await serial processing of multiple threads9//Wait until the statement after the await has finished executing10//To execute the other statements of this thread11//Step 212Await Task.run (NewAction (M2));Console.WriteLine ("Current Thread ID is {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);14//Step 6count++;16//Step 7Console.WriteLine ("M1 Step is {0}", count);18}1920PublicStaticvoidM2 ()21st{Console.WriteLine ("Current Thread ID is {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);23 //step 324 System.Threading.Thread.Sleep (25 //step 426 count++< Span style= "color: #000000;" >; 27 //step 528 Console.WriteLine (m2 Step is {0} "29 }30}
In the time series diagram we can see that there are two threads interacting, as shown in:
With async and await, the preceding code is executed in the following order:
In general, this global variable is thread-safe if there are only read operations on global variables and static variables in each thread, and if multiple threads perform read and write operations on a variable at the same time, it is generally necessary to consider thread synchronization, otherwise it may affect thread safety.
How does C # guarantee thread safety under multithreading?