Thread is also crazy ----- thread synchronization (2), ----- Thread Synchronization

Source: Internet
Author: User

Thread is also crazy ----- thread synchronization (2), ----- Thread Synchronization
Kernel Mode Construction

As mentioned earlier, kernel mode construction is much slower than user mode construction, one reason is that they require the cooperation of the Windows operating system, another reason is that every method called on the kernel object causes the calling thread to switch from the managed code to the local user mode code and then to the background kernel mode code, which requires a lot of CPU time.

However, the kernel mode has the following advantages:

1. When the resource competition is detected, windows will block the lost thread

2. Synchronization of threads running in different processes on a machine

3. prevent unauthorized account from accessing the thread

4. A blocked thread can specify a timeout value.

Event and semaphore are two types of Kernel Mode thread synchronization structures.

WaitHandle abstract base class, the only function is to wrap a windows Kernel Object handle, inherit WaitHadle objects can be divided into three types: 1. event construction (AutoResetEvent, ManualResetEvent) 2. semaphore construction 3. mutex Construction

Event Construction

AutoResetEvent and ManualResetEvent: the basic working principle is that multiple threads hold the same XXXResetEvent. Before this XXXResetEvent is not set, all threads are suspended in WaitOne; after the XXXResetEvent is set, one or all of the suspended threads resume execution.

 

Example of AutoResetEvent:

1 AutoResetEvent autoResetEvent = new AutoResetEvent (true); // true by default, the first unsuspended thread is executed 2 3 tasks. factory. startNew () => 4 {5 Console. writeLine ("thread 1: I have started the task and executed it, wait for the instruction"); 6 autoResetEvent. waitOne (); 7 Console. writeLine ("thread 1 task execution ends"); 8 autoResetEvent. set (); 9}); 10 11 12 tasks. factory. startNew () => 13 {14 Console. writeLine ("Thread 2: I have started the task and executed it, wait for the instruction"); 15 // Thread. sleep (1000); 16 autoResetEvent. waitOne (); 17 Console. writeLine ("thread 2 task execution ended"); 18}); 19 Console. writeLine ("program ended"); 20 Console. readLine ();

 

ManualResetEvent example:

1 ManualResetEvent autoResetEvent = new ManualResetEvent (false); // true: by default, the first thread not suspended 2 3 tasks is executed. factory. startNew () => 4 {5 Console. writeLine ("thread 1: I have started the task and executed it, wait for the instruction"); 6 autoResetEvent. waitOne (); 7 Console. writeLine ("thread 1 Task execution ended"); 8 9}); 10 Task. factory. startNew () => 11 {12 Console. writeLine ("Thread 2: I have started the task and executed it, wait for the instruction"); 13 // Thread. sleep (1000); 14 autoResetEvent. waitOne (); 15 Console. writeLine ("thread 2 task execution ended"); 16}); 17 Console. writeLine (""); 18 Thread. sleep (1000); 19 autoResetEvent. set (); 20 Console. writeLine ("program ended"); 21 Console. readLine ();

I remember there was an interview question. When we created four threads and printed ABCD three times in sequence, we got the question of thread synchronization. You can think about how to solve it.

 

Semaphore Construction

Construction principle: the int32 variable is maintained through the kernel. When the semaphore is 0, the waiting thread on the semaphore will be blocked. When the semaphore is greater than 0, the blocking will be lifted, when the threads waiting on the semaphore are in contact with the obstruction, the kernel will automatically subtract 1 from the semaphore count.

 

1 Semaphore semaphore = new Semaphore (0, Int32.MaxValue); // specify the maximum concurrency of 2 3 tasks. factory. startNew () => 4 {5 Console. writeLine ("thread 1: I have started the task and executed it, wait for the instruction"); 6 semaphore. waitOne (); 7 Console. writeLine ("thread 1 task execution ends"); 8 semaphore. release (); 9 10}); 11 Task. factory. startNew () => 12 {13 Console. writeLine ("Thread 2: I have started the task and executed it, wait for the instruction"); 14 // Thread. sleep (1000); 15 semaphore. waitOne (); 16 Console. writeLine ("thread 2 task execution ended"); 17}); 18 Console. writeLine ("1 s before notifying the thread to execute the task"); 19 semaphore. release (); 20 Console. writeLine ("program ended"); 21 Console. readLine ();

 

Mutex Construction

Similar to AtuoResetEvent, the principle is that only one waiting thread can be released at a time, but mutual exclusion has some additional logic, which makes it more complex than the previous construction. First, the Mutex object queries the Int32 ID of the call thread, recording which thread obtained it. When a thread calls ReleaseMutex, mutex ensures that the call thread is the thread that obtains the Mutex, otherwise, the status of the mutex object will change. In addition, the Mutex object maintains a recursive count, indicating how many times the thread that owns the Mutex has it. If a thread currently has a mutex, then the thread waits on the mutex again, and the count will increase progressively, which allows the thread to continue running.

Construct a Mutex recursive lock:

1 class MutexLock: IDisposable 2 {3 private readonly Mutex mutex; 4 5 public MutexLock () 6 {7 mutex = new Mutex (); 8} 9 10 public void Enter () 11 {12 mutex. waitOne (); 13 // sit anywhere 14 Leave (); 15 mutex. releaseMutex (); 16 17} 18 19 public void Leave () 20 {21 mutex. waitOne (); 22 // sit on anything at Will 23 mutex. releaseMutex (); 24} 25 26 public void Dispose () 27 {28 mutex. dispose (); 29} 30}

 

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.