"Reprint" 5 days no longer fear of multi-threaded-fourth day signal volume

Source: Internet
Author: User
Tags semaphore

Today to organize the "signal" of the relevant knowledge, in fact, it is quite interesting to think about, lock, mutual exclusion, signal volume can achieve thread synchronization, in the framework of the main there are three.

<1>:manualresetevent

<2>:autoresetevent

<3>: Semaphore

OK, here's a look at the use of these gadgets.

One: ManualResetEvent

The object has two semaphore states true and false, and curious we certainly want to know what the difference is between true and false, and later in the example, there are three ways worth learning.

1:waitone

This method is used to block the thread, the default is an indefinite block, sometimes we do not want to do so, but instead of a time-out blocking method, if the timeout to abandon the blocking, which also avoids the indefinite

Wait for the embarrassment.

2:set

Manually modify the semaphore to true, that is, resume thread execution.

3:reset

Manually modify the semaphore to false to suspend thread execution.

Well, here's an example to illustrate.

<1> the initial semaphore is false,waitone with an indefinite block, and can be found to interact between threads.

1 public class Example
2 {
3 public static void Main ()
4 {
5 Thread t = new thread (Run);

7 t.name = "Jack";

9 Console.WriteLine ("Current time: {0} {1} {1}, I am the main thread, receive please answer.") ", DateTime.Now, T.name);

T.start ();

Thread.Sleep (5000);

Mr. Set ();

Console.read ();
(+ }

static ManualResetEvent Mr = new ManualResetEvent (false);

static void Run ()
% {
Mr. WaitOne ();

Console.WriteLine ("\ n Current time: {0} main thread, main thread, {1} received! ", DateTime.Now, Thread.CurrentThread.Name);
+ }
28}

<2> the initial signal volume was true,waitone with an indefinite block, and the experiment found that WaitOne was not actually blocked.

static ManualResetEvent Mr = New ManualResetEvent (true);

<3> the initial signal volume is false,waitone with a timeout of 2s, although the main thread to wait for the 5s to set operation, but WaitOne can't wait to advance the execution.

1 public class Example
2 {
3 public static void Main ()
4 {
5 Thread t = new thread (Run);

7 t.name = "Jack";

9 Console.WriteLine ("Current time: {0} {1} {1}, I am the main thread, receive please answer.") ", DateTime.Now, T.name);

T.start ();

Thread.Sleep (5000);

Mr. Set ();

Console.read ();
(+ }

static ManualResetEvent Mr = new ManualResetEvent (false);

static void Run ()
% {
Mr. WaitOne (2000);

Console.WriteLine ("\ n Current time: {0} main thread, main thread, {1} received! ", DateTime.Now, Thread.CurrentThread.Name);
+ }
28}


Two: AutoResetEvent

In the VS Object Browser, we find that both AutoResetEvent and ManualResetEvent inherit from EventWaitHandle, so the basic functionality is the same, but it's worth noting

One difference is that WaitOne will change the value of the semaphore, for example, if the initial semaphore is true, if the WaitOne timeout semaphore will automatically turn false, and ManualResetEvent will not.

1 public class Example
2 {
3 public static void Main ()
4 {
5 Thread t = new thread (Run);

7 t.name = "Jack";

9 T.start ();

Console.read ();
-- }

The static AutoResetEvent ar = new AutoResetEvent (true);

static void Run ()
+ {
var state = ar. WaitOne (+, true);

Console.WriteLine ("My current semaphore status: {0}", state);

state = ar. WaitOne (+, true);

Console.WriteLine ("I hate you, ignore me, your present status is: {0}", state);

+ }
27}

Three: Semaphore

This thing is new to. NET 4.0, which controls the number of accesses to threads, the default constructor is Initialcount and Maximumcount, which indicates the number of semaphores that are set by default and

The maximum number of semaphores, in fact, the inside is the use of counters to allocate the signal volume, when you WaitOne, the signal volume is reduced, when the release, the signal volume from the increase, however

When the semaphore is 0, the subsequent thread cannot get the WaitOne, so it must wait for the previous thread to release it through release.

Well, here's an example to illustrate:

<1> Initialcount=1,maximuncount=10,waitone is waiting indefinitely.

1 namespace ConsoleApplication3
2 {
3 Class Program
4 {
5 static void Main (string[] args)
6 {

8 Thread T1 = new Thread (RUN1);
9 t1. Start ();

One thread t2 = new Thread (RUN2);
T2. Start ();

Console.read ();
}

The static Semaphore sem = new Semaphore (1, 10);

static void Run1 ()
{
SEM. WaitOne ();

Console.WriteLine ("Hello, I am Run1");
+ }

-static void Run2 ()
{
SEM. WaitOne ();

Console.WriteLine ("Hello, I am Run2");
+ }
+ }
33}

Our tragic Discovery T2 thread cannot execute, we know that WaitOne is equivalent to a self-reducing semaphore, but the default semaphore count is 1, so T2 want to execute must wait for T1 to be released through release.

1         static void Run1 ()
2 {
3 SEM. WaitOne ();

5 Console.WriteLine ("Hello, I am Run1");

7 SEM. Release ();
8 }

Maybe some students want to ask, I am not set up maximuncount=10 it? Why is it not playing a role? Yes, it doesn't work by default, we have to intervene manually,

We know that calling the release method is equivalent to adding a semaphore, but the release has an overload that can specify a self-increment to maximuncount semaphore, where I'm on the main thread

Release (10) to see the effect.

1 namespace ConsoleApplication3
2 {
3 Class Program
4 {
5 static void Main (string[] args)
6 {

8 Thread T1 = new Thread (RUN1);
9 t1. Start ();

One thread t2 = new Thread (RUN2);
T2. Start ();

Thread.Sleep (1000);

SEM. Release (10);

Console.read ();
+ }

static Semaphore sem = new Semaphore (1, 10);

All static void Run1 ()
{
SEM. WaitOne ();

Console.WriteLine ("Hello, I am Run1");
(+ }

static void Run2 ()
{
SEM. WaitOne ();

Console.WriteLine ("Hello, I am Run2");
+ }
(+ }
37}


<2> semaphore naming, upgrade process interaction.

Found in the VS Object Browser semaphore is the inheritance word WaitHandle, and WaitHandle encapsulates some of the Win32 synchronization mechanism, so when we give Semaphore name

will be visible in the system, here is an example, copy the following code, run two programs.

1 namespace ConsoleApplication3
2 {
3 Class Program
4 {
5 static void Main (string[] args)
6 {

8 Thread T1 = new Thread (RUN1);
9 t1. Start ();

One thread t2 = new Thread (RUN2);
T2. Start ();

Console.read ();
}

the static Semaphore sem = new Semaphore (3, "cnblogs");

static void Run1 ()
{
SEM. WaitOne ();

Console.WriteLine ("Current time: {0} Hello everyone, I am Run1", datetime.now);
+ }

-static void Run2 ()
{
SEM. WaitOne ();

Console.WriteLine ("Current time: {0} Hello everyone, I am Run2", datetime.now);
+ }
+ }
33}

Yes, I set the semaphore is 3, so only three threads hold WaitOne, the subsequent threads can only wait.

Reprint Address: http://www.cnblogs.com/huangxincheng/archive/2012/03/17/2404181.html

"Reprint" 5 days no longer fear of multi-threaded-fourth day signal volume

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.