Multi-thread C # How to Ensure thread security ?,

Source: Internet
Author: User

Multi-thread C # How to Ensure thread security ?,

Compared with a single thread, multi-threaded programming has a special problem, that is, thread security. The so-called thread security means that if multiple threads run simultaneously in the process where your code is located, these threads may run the code at the same time. If each running result is the same as that of a single thread, and the values of other variables are the same as expected. Thread security issues are caused by global variables and static variables.

To ensure the security of access to static variables in the case of multithreading, you can use the locking mechanism to ensure the security, as shown below:

1 // static global variable to be locked 2 private static bool _ isOK = false; 3 // lock can only lock one reference type variable 4 private static object _ lock = new object (); 5 static void MLock () 6 {7 // multithreading 8 new System. threading. thread (Done ). start (); 9 new System. threading. thread (Done ). start (); 10 Console. readLine (); 11} 12 13 static void Done () 14 {15 // lock can only lock one reference type variable 16 lock (_ lock) 17 {18 if (! _ IsOK) 19 {20 Console. WriteLine ("OK"); 21 _ isOK = true; 22} 23} 24}

You must note that Lock can Lock only one object of the reference type. In addition to the lock mechanism, The async and await methods are added to C # of higher versions to ensure thread security, as shown below:

1 public static class AsynAndAwait 2 {3 // step 1 4 private static int count = 0; 5 // use async and await to ensure the static variable count security in multithreading 6 public async static void M1 () 7 {8 // async and await perform serial processing on multiple threads. 9 // wait until the await statement is executed, and then execute the other statements of this thread. 11 // step 212 await Task. run (new Action (M2); 13 Console. writeLine ("Current Thread ID is {0}", System. threading. thread. currentThread. managedThreadId); 14 // step 615 count ++; 16 // step 717 Console. writeLine ("M1 Step is {0}", count); 18} 19 20 public static void M2 () 21 {22 Console. writeLine ("Current Thread ID is {0}", System. threading. thread. currentThread. managedThreadId); 23 // step 324 System. threading. thread. sleep (3000); 25 // step 426 count ++; 27 // step 528 Console. writeLine ("M2 Step is {0}", count); 29} 30}

In the sequence diagram, we can know that there are two threads interacting, as shown in:

After async and await are used, the execution sequence of the above Code is as follows:

 

If each thread only performs read operations on global variables and static variables without write operations, this global variable is thread-safe; if multiple threads perform read/write operations on a variable at the same time, thread synchronization is generally considered; otherwise, thread security may be affected.

The level is limited. Hope you can kindly advise me! If you think it is good, please click recommendation and follow!
Source: http://www.cnblogs.com/isaboy/
Disclaimer: The copyright of this article is shared by the author and the blog Park. You are welcome to reprint it. However, you must keep this statement without the author's consent and provide the original article connection clearly on the article page, otherwise, you are entitled to pursue legal liability.

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.