How does C # guarantee thread safety under multithreading?

Source: Internet
Author: User

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?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.