Recommendation 6 for improving the C # program: Use semaphores in thread synchronization

Source: Internet
Author: User

The so-called thread synchronization means that multiple threads wait for an object (also known as locking the object) until the object is unlocked. In C #, object types are divided into reference types and value types. CLR waits for these two types are different. We can simply understand that in CLR, the value type cannot be locked, that is, it cannot be executed on a value type object. The Wait Mechanism on the reference type is divided into two types: Lock and signal synchronization.

Lock: Use the keyword lock and type Monitor. There is no substantive difference between the two. The former is actually the syntactic sugar of the latter. This is the most common synchronization technology;

We recommend that you talk about signal synchronization. The types involved in the signal synchronization mechanism are inherited from the abstract class WaitHandle. These types include EventWaitHandle (converted to AutoResetEvent, ManualResetEvent), Semaphore, and Mutex. See the class diagram 6-3:

Graph synchronization function class diagram

EventWaitHandle (subclass: AutoResetEvent, ManualResetEvent), Semaphore, and Mutex all inherit from WaitHandle. Therefore, they have the same underlying principle and maintain a system kernel handle. However, we still need to make a simple distinction between the three types.

EventWaitHandle: maintains a Boolean object generated by the kernel (we call it a "Block state"). If its value is false, the thread waiting on it will be blocked. You can call the Set Method of the type to Set its value to true to remove blocking. The AutoResetEvent and ManualResetEvent subclasses of the EventWaitHandle type are not very different. We recommend that you elaborate on them to use semaphores correctly.

Semaphore maintains an integer variable generated by the kernel. If its value is 0, the thread waiting for it will be blocked. If its value is greater than 0, the blocking will be lifted, every time a thread is blocked, its value is reduced by 1.

EventWaitHandle and Semaphore provide the thread synchronization function in a single application domain. Mutex is different in that it provides us with the ability to block and remove blocked threads across application domains.


1: a simple example of using the signal mechanism to provide Thread Synchronization

A simple example of using the signal mechanism to provide thread synchronization is as follows:

AutoResetEvent autoResetEvent= NewAutoResetEvent (False);

Private VoidButtonStartAThread_Click (ObjectSender, EventArgs e)
{
Thread tWork= NewThread (()=>
{
Label1.Text= "Thread startup..." +Environment. NewLine;
Label1.Text+ = "Start to process some practical work" +Environment. NewLine;
//Omitting work code
Label1.Text+ = "I started to wait for other threads to give me a signal before I was willing to continue." +Environment. NewLine;
AutoResetEvent. WaitOne ();
Label1.Text+ = "I continue to do some work, and then it's over!";
//Omitting work code
});
TWork. IsBackground= True;
TWork. Start ();
}

Private VoidButtonSet_Click (ObjectSender, EventArgs e)
{
//A signal is sent to the thread waiting on autoResetEvent.
AutoResetEvent. Set ();
}

This is a simple Winform program. one of the buttons is responsible for opening a new thread, and the other is responsible for sending signals to the newly opened thread. Now let's explain in detail what happened here.

AutoResetEvent autoResetEvent = new AutoResetEvent(false);

This Code creates a synchronization object autoResetEvent, which sets its default block status to false. This means that any thread waiting on it will be blocked. The so-called waiting is the application in the thread:

autoResetEvent.WaitOne();

This indicates that tWork starts to wait for signals from anywhere else on autoResetEvent. When the signal comes, tWork starts to work, otherwise it will wait (Block ). Next we can see that in the main thread (in this example, the UI thread, which is a "another thread" relative to the thread tWork "):

autoResetEvent.Set();

The main thread sends a signal to the tWork context of the thread waiting on the autoResetEvent through the above Code, which sets the blocking status of tWork to true. TWork receives this signal and starts to work.

This example is quite simple, but the working principle of the signal mechanism has been fully explained.


2: differences between AutoResetEvent and ManualResetEvent

AutoResetEvent and ManualResetEvent have the following differences: the former automatically sets its block status to false after the signal is sent (that is, the Set method is called), while the latter needs to be manually Set. An example is provided to illustrate the difference:

        AutoResetEvent autoResetEvent = new AutoResetEvent(false);

private void buttonStartAThread_Click(object sender, EventArgs e)
{
StartThread1();
StartThread2();
}

private
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.