How to ensure thread safety in C # under shared 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:

Static global variables that require locking

private static bool _isok = FALSE;        Lock can only lock a reference type variable        private static Object _lock = new Object ();        static void MLock ()        {            //multithreading            new System.Threading.Thread (done). Start ();            New System.Threading.Thread (done). Start ();            Console.ReadLine ();        }        static void Done ()        {            //lock can only lock a reference type variable            lock (_lock)            {                if (!_isok)                {                    Console.WriteLine ("OK");                    _isok = True;}}        }

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:

public static class asynandawait{//step 1 private static int count = 0        ;            Guaranteed multithreading with Async and await static variable count security public async static void M1 () {//async and await serial processing of multiple threads            Wait until the statement after the await is completed//before the other statements of this thread are executed//step 2 await Task.run (new Action (M2));            Console.WriteLine ("Current Thread ID is {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);            Step 6 count++;        Step 7 Console.WriteLine ("M1 step is {0}", count); public static void M2 () {Console.WriteLine (' Current Thread ID ' is {0} ', System.Threading.Thread .            Currentthread.managedthreadid);            Step 3 System.Threading.Thread.Sleep (3000);            Step 4 count++;        Step 5 Console.WriteLine ("M2 step is {0}", count); }}

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

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.