C # Learn from the story: thread (4)

Source: Internet
Author: User

C # Learn from the story: thread (4)

Thread Synchronization (medium): Introduction to the synchronization tool class

  • 1. Review of the previous Article
  • 2. Continue to introduce the monitor class in the primitive kernel mode.
  • 3. Synchronization handle: waithandle
  • 4 eventwaithandle, autoresetevent and manualresetevent
  • 5. mutex synchronization class
  • 6. Differences between mutex and monitor
  • 7. Select the required synchronization tool.
  • 8. Summary in this Chapter

 

 

1. Review of the previous Article

Sorry, I haven't written a blog for a long time. Because my work is too busy, I recently fell short. Let's start the previous article and introduce some important concepts of thread synchronization to you:

The primitive kernel mode, the primitive user mode, and atomicity are introduced one after another. The validated, interloced, and readerwriterlock classes in the primitive user mode are also simple.

This section describes the lock keywords in the basic kernel mode. We will continue to learn more about other synchronization tool classes.

 

2. Continue to introduce the monitor class in the primitive kernel mode.

First, let everyone have a preliminary impression:

The monitor class is also an important class in the synchronization mechanism. It belongs to the primitive kernel mode and is closely related to the lock keyword in the previous chapter.

The exclusive lock is used to synchronize data in the shared zone. When a thread enters the shared zone, it will gain control of the exclusive lock. Other threads must wait. Note that there are two important lines here.

The progress status must be described below

1: waiting queue:

The thread waiting to enter the shared area will first enter the waiting queue, waiting for the thread holding the exclusive lock to notify a waiting thread to enter the ready queue. Note (only

Only threads with exclusive locks can exchange notifications, and even the thread can wake up a bunch of waiting threads to enter the ready queue)

2: ready queue

Wait for a thread in the queue to be awakened by the exclusive lock and put into the ready queue. Wait for the opportunity to obtain the exclusive lock so that a cycle can be connected,

The thread starts from waiting to waking up to the ready state, then obtains the exclusive lock for operations in the shared area, and then submits the exclusive lock for waiting or sleep until it is awakened again.

Here, we emphasize that monitor is a synchronization class that is very prone to deadlock. The reason is:

1. When a thread tries to request a lock object, it is not in a waiting queue, but a ready queue. If you need to enter the waiting queue, you must use the wait method.

2. When a thread releases the lock object, it will not notify the threads in the waiting queue to enter the ready queue. The palse method is required.

3. When the thread starts, the thread is in the ready state.

4. Even if a thread in the ready state is selected by the CPU, once the data is locked, the thread still cannot obtain control.

 

As a matter of fact, after you understand the cause, you have already understood the monitor. This is exactly the monitor mechanism.

After understanding the above mechanism, you can begin to understand several important methods of this class:

Monitor. Enter (object );

This method aims to announce that the current thread enters the critical section, holds the exclusive lock, and other threads continue to wait until the thread leaves the shared area to hand over the exclusive lock to a thread in the ready queue.

Monitor. Exit (object );

After the thread holding the shared lock executes the task, the thread leaves the shared zone through this method. before leaving, it can operate to wake up one or more waiting threads.

Monitor. palse (object) and monitor. palse (object)

These two methods are complex and similar, that is, the method for awakening (changing) the status of other threads. The thread holding the exclusive lock uses these two methods to notify other threads to enter the ready queue and leave the waiting queue.

Monitor. Wait (object)

This method is also very important. If the thread in the shared zone executes the wait method, the thread will be placed in the waiting queue, thus losing control of the exclusive lock, the next thread in the ready queue enters the critical section.

Monitor. tryenter (object, Boolean ))

Sometimes other threads want to actively strive for control of the exclusive lock through an attempt. This method can implement this function and use a bool parameter to indicate whether exclusive lock exists.

Text introduction to let everyone better understand the nature of the monitor class, next we will have a very simple code to give us a more in-depth understanding

/// <Summary> /// enable two write threads, demonstration of two read threads /// </Summary> /// <Param name = "ARGs"> </param> static void main (string [] ARGs) {thread T1 = new thread (New threadstart (writeinsharearea); thread T3 = new thread (New threadstart (writeinsharearea); thread t2 = new thread (New threadstart (read )); thread t4 = new thread (New threadstart (read); console. writeline ("T1's id = {0}", t1.managedthreadid); console. writeline ("T2's id = {0}", t2.managedthreadid); console. writeline ("T3's id = {0}", t3.managedthreadid); t1.start (); t3.start (); t2.start (); t4.start (); console. read () ;}/// <summary> // read data. First, let the read thread wait. After the write thread finishes writing the pulse method, wake up the read thread to continue working // </Summary> Private Static void read () {While (true) {Monitor. enter (lockobj );
// When the read thread is started, the default ready queue // when the read thread is executed here, it will be suspended and enter the waiting queue monitor. wait (lockobj, 4000); console. writeline ("thread {0} can read Nao", thread. currentthread. managedthreadid); console. writeline ("thread {0} reading ............... ", thread. currentthread. managedthreadid); thread. sleep (3000); monitor. exit (lockobj) ;}/// <summary> // write data. After the write thread finishes writing the pulse method, wake up the read thread to continue working // </Summary> Private Static void writeinsharearea () {While (true) {thread. sleep (1000); monitor. enter (lockobj); console. writeline ("thread {0} change data Nao", thread. currentthread. managedthreadid); console. writeline ("thread {0} Changing ............... ", thread. currentthread. managedthreadid); thread. sleep (1000); // wake up the read thread to enter the ready queue monitor. pulse (lockobj); monitor. exit (lockobj );}}

Execution result:

 

 

3. Synchronization handle: waithandle

Waithandle is the base class of many synchronization objects in this chapter, including the autoresetevent, manualresetevent, mutex, and semaphore in the previous sections,

Waithandle is an abstract class. Its main functions can be seen literally. It is nice to wait for a handle. waithandle is amazing. It contains a Win32 kernel object handle and thread.

Will wait for the message of the kernel object. Of course, the kernel object will also wait for the signal to be received. Once the signal is received, the current thread will be notified. This is a complicated Operating System Scheduling Principle. For details, refer

Windows core programming and other books continue to have a deep understanding, this article aims to explain the concept of waithandle and some simple introduction, here for the waithandle for example:

When you want to cross the road, if the signal light is red, you can only wait. If it turns into a green light, you can pass. In fact, waithandle is used for the traffic light, smart you

Surely, can we put the thread synchronization signal lights into the thread pool? Haha, of course, you can not only put one, but also put a bunch of waithadle objects. To put it bluntly: waithadle

There are also two signals "signaled" and "nonsignaled". The former can be understood as a green light, while the waitone method is invalid when the green light status, the current thread is not blocked, and the latter can be understood as a red light, bottom

When a layer Kernel Object receives a signal, it notifies the current thread that it can enter the shared area (critical section) and the rest of the thread to wait. However, based on the abstract class, waithandle does not have the set method to wake up the thread,

The Child class is implemented, so waithandle still fully embodies its "and so on, until it prompts that it can pass through or directly crash (timeout exception)" Features

Since waithandle only blocks waiting, let's look at several of its wonderful methods:

1 bool waitone (): waits for a kernel object specified by waithandle to receive a signal and returns true. Otherwise, false is returned.

2 bool waitall (): returns true after all kernel objects in waithandle [] receive signals; otherwise, returns false.

3 bool waitany (); returns true if all kernel objects in waithandle [] receive signals; otherwise, returns false.

4 bool signalandwait (): This method cannot be clearly expressed in text, but you can first understand it as follows: automatically sends information to the kernel object, waiting for another kernel object to receive the signal,

If another kernel object receives a signal, true is returned, which involves a complicated "Mixed Lock" mechanism. Therefore, this article will not detail it. The next chapter will introduce the Mixed Lock Mechanism in detail.

Next, let's take a look at the structure of several Derived classes of waithandle, which will be introduced one by one later:

Eventwaithandle

Autoresetevent

Manualresetevent

Mutex

Semaphore (detailed in the following chapter)

The last figure shows how waithandle works.

 

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.