C # Multithreading: In-depth understanding of thread synchronization Lock,monitor,mutex, synchronization events and wait handles (medium)

Source: Internet
Author: User
Tags net thread semaphore

This article continues to describe the use of the Waithandler class and its subclasses mutex,manualresetevent,autoresetevent: NET thread synchronization way more people see a dazzling, how to understand it? In fact, we put aside. NET environment to look at thread synchronization, nothing is to do two operations: one is mutual exclusion/locking, the purpose is to ensure that the critical section code operation of "Atomicity", and the other is a semaphore operation, the purpose is to ensure that multiple threads in a certain order, such as the producer thread to be executed before the consumer thread. NET thread synchronization class is nothing more than the encapsulation of the two methods, the purpose of the final analysis can be attributed to the implementation of mutual exclusion/locking or signal lights in both ways, but their application is not the case. Below we understand Waithandler and its subclasses based on the hierarchy of the class.  
      1.waithandler 

      WaitHandle is a common ancestor of Mutex,semaphore,eventwaithandler,autoresetevent,manualresetevent, which encapsulates Win32 synchronous handle kernel objects, That is, the managed version of these kernel objects. &NBSP

      threads can block on a single wait handle by calling the method of the Waithandler instance WaitOne. Additionally, the Waithandler class overloads the static method to wait for all specified wait handles to be collected to signal waitall, or to wait for a specified wait handle to be collected to the signal waitany. These methods provide a time-out interval to discard the wait, an opportunity to exit the synchronization context before entering the wait, and allow other threads to use the synchronization context. Waithandler is an abstract class in C # and cannot be instantiated. &NBSP

      2.EventWaitHandler vs. ManualResetEvent vs. AutoResetEvent (sync events)  

      Let's take a look at the implementation of the two subclasses ManualResetEvent and AutoResetEvent in the. NET framework:  

C # code
  1. Implementation of the ManualResetEvent class in the. NET Framework
  2. [ComVisible (True), HostProtection (SecurityAction.LinkDemand, synchronization = true, externalthreading = true)]
  3. Public Sealed class Manualresetevent:eventwaithandle
  4. {
  5. //Methods
  6. Public ManualResetEvent (bool initialstate): base (initialstate, Eventresetmode.manualreset)
  7. {
  8. }
  9. }
  10. implementation of AutoResetEvent class in//.net framework
  11. [ComVisible (True), HostProtection (SecurityAction.LinkDemand, synchronization = true, externalthreading = true)]
  12. Public Sealed class Autoresetevent:eventwaithandle
  13. {
  14. //Methods
  15. Public AutoResetEvent (bool initialstate)
  16. : Base (initialstate, Eventresetmode.autoreset)
  17. {
  18. }
  19. }


Originally ManualResetEvent and AutoResetEvent both inherit from Eventwaithandler, their only difference is that the parent class Eventwaithandler constructor parameters EventResetMode different, So we just have to figure out the parameter EventResetMode value is not the same, the Eventwaithandler class control thread synchronization behavior is different, two sub-classes are also clear. For the sake of description, we do not introduce the two modes of the parent class, but introduce the subclass directly.

ManualResetEvent and AutoResetEvent in common:
1) The Set method sets the event state to the signaled state, allows one or more waiting threads to continue, the Reset method sets the event state to a non-terminating state, causes the thread to block, and WaitOne blocks the current thread until the waithandler of the current thread receives the event signal.
2) The initial state can be determined by the parameter value of the constructor, or, if true, the event is signaled so that the thread is in a non-blocking state, and false to a blocked state.
3) If a thread calls the WaitOne method, the thread receives a signal when the event state is signaled and continues down execution.

Different points of ManualResetEvent and AutoResetEvent:
1) Autoresetevent.waitone () only allow one thread at a time, and when a thread gets a signal, AutoResetEvent automatically and sends the signal to the non-sending state, the other thread that calls WaitOne only continues to wait, This means that AutoResetEvent only wakes up one thread at a time;
2) ManualResetEvent can wake up multiple threads, because when a thread calls the Manualresetevent.set () method, the other thread that calls WaitOne gets the signal to continue executing, The ManualResetEvent does not automatically reset the signal to not send.
3) that is, unless the Manualresetevent.reset () method is called manually, ManualResetEvent will remain signaled, and ManualResetEvent can wake up multiple threads at the same time to continue execution.

Example scenario: Zhang San, Li 42 good friends to the restaurant to eat, two people ordered a Kung Pao chicken, Kung Pao chicken to do a good time, Zhang San, John Doe do not want to be silly, all concentrate on the mobile phone game, thought Kung Pao chicken is ready, the waiter will definitely call us. After the waiter served, Dick and Harry began to enjoy the delicious food, the meal was eaten up, they called the waiter came to pay. We can abstract from this scene three threads, Zhang San thread, John Doe thread and waiter thread, they need to synchronize: Waiter serving, Zhang San, John Doe began to enjoy Kung Pao chicken----eat good after the waiter came to pay. What does this sync use? ManualResetEvent or AutoResetEvent? Through the above analysis is not difficult to see, we should use ManualResetEvent to synchronize, the following is the program code:

The story of Dick and Harry Dinner

C # code
  1. Public class Eventwaittest
  2. {
  3. private string name; //Customer name
  4. //private static AutoResetEvent eventwait = new AutoResetEvent (false);
  5. private static ManualResetEvent eventwait = new ManualResetEvent (false);
  6. private static ManualResetEvent Eventover = new ManualResetEvent (false);
  7. Public eventwaittest (string name)
  8. {
  9. this.name = name;
  10. }
  11. public static void Product ()
  12. {
  13. Console.WriteLine ("Waiter: Chef in cooking, two-bit wait");
  14. Thread.Sleep (2000);
  15. Console.WriteLine ("Waiter: Kung Pao Chicken Good");
  16. Eventwait.set ();
  17. While (true)
  18. {
  19. if (Eventover.waitone (), false)
  20. {
  21. Console.WriteLine ("Waiter: two Please pay");
  22. Eventover.reset ();
  23. }
  24. }
  25. }
  26. public Void Consume ()
  27. {
  28. While (true)
  29. {
  30. if (Eventwait.waitone (), false)
  31. {
  32. Console.WriteLine (THIS.name + ": Start eating Kung Pao chicken");
  33. Thread.Sleep (2000);
  34. Console.WriteLine (THIS.name + ": Kung Pao Chicken eaten up");
  35. Eventwait.reset ();
  36. Eventover.set ();
  37. Break ;
  38. }
  39. Else
  40. {
  41. Console.WriteLine (THIS.name + ": Waiting for the serving boring first play will mobile games");
  42. }
  43. }
  44. }
  45. }
  46. public class App
  47. {
  48. public static void Main (string[] args)
  49. {
  50. Eventwaittest Zhangsan = new Eventwaittest ("Zhang San");
  51. Eventwaittest lisi = new Eventwaittest ("John Doe");
  52. Thread T1 = new Thread (new ThreadStart (Zhangsan.  consume));
  53. Thread t2 = new Thread (new ThreadStart (Lisi.  consume));
  54. thread t3 = new Thread (new ThreadStart (eventwaittest.product));
  55. T1. Start ();
  56. T2. Start ();
  57. T3. Start ();
  58. Console.read ();
  59. }
  60. }


After compiling to see the results of the operation, as expected, the console output is:
Waiter: The chef is cooking, two people wait ...
Zhang San: Waiting for the food boring first play mobile games
John Doe: Waiting for the food boring first play mobile games
Zhang San: Waiting for the food boring first play mobile games
John Doe: Waiting for the food boring first play mobile games
Waiter: Kung Pao chicken.
Zhang San: Start eating Kung Pao chicken
John Doe: Start eating Kung Pao chicken
Zhang San: Kung Pao Chicken eaten up
John Doe: Kung Pao Chicken eaten up
Waiter: Two people please pay

What if you use AutoResetEvent for synchronization? What kind of results will happen? I'm afraid Zhang San and John Doe are going to fight, one to enjoy the delicious Kung Pao chicken, and the other to pay the bill while still playing games. Interested friends can remove the comment line code comment, and the following line of code to comment out, run the program to see what the results will appear.

3.Mutex (Mutex)

Mutexes and Eventwaithandler have common parent class Waithandler classes, and they also have similar functions in sync, not to be mentioned here. The salient feature of mutexes is the ability to have exclusive access to resources across application domain boundaries, which can be used to synchronize threads in different processes, which is at the expense of more system resources, of course.

One application of this cross-process synchronization is to restrict the simultaneous opening of two identical programs on the same computer. The implementation can refer to the use of a mutex or process to restrict users to open two programs on a single computer.

C # Multithreading: In-depth understanding of thread synchronization Lock,monitor,mutex, synchronization events and wait handles (medium)

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.