AutoResetEvent and ManualResetEvent, autoresetevent

Source: Internet
Author: User

AutoResetEvent and ManualResetEvent, autoresetevent

Original http://www.360doc.com/content/13/0829/14/4513754_310723961.shtml

I. Role

AutoResetEvenT andManualResetEventIt can be used to control the thread pause or continue. There are three important methods:WaitOne,SetAndReset.

The official definitions of these three methods are not easy to understand, such as termination or non-termination. Here, we describe it in a simple and easy-to-understand concept.

 

2. Metaphor

If we compare each thread to a car,AutoResetEventAndManualResetEventIt is the toll station on the road.

Where:

ResetDisable the traffic at the gate of the toll station (the traffic is charged only when the traffic is intercepted );

WaitOneThe toll collector waits for the next vehicle to come over (and then charges );

SetOpen the gate of the toll station (if you pay the money, let the past ).

 

Iii. Differences between AutoResetEvent and ManualResetEvent

SinceAutoResetEventAndManualResetEventAre all toll stations, so what are the differences between them?

As the name suggests,AutoThat is, automatic,ManualThat is, manually, andResetAccording to the above metaphor, the brake is closed, that is, the former can automatically close the brake, and the latter needs to manually close the brake.

Automatic shutdown: After a car passes the payment, the brake will automatically close and wait for the next car to pay the fee. That is to say, each vehicle has to go through the following steps: blocked> paid> pass> closed

Manually close the brakes: When a brake is opened, the brake is not automatically closed.ManualResetEvent. Reset ()Method), the vehicle will pass one by one ......

 

SoWaitOneThe charging operation depends on whether the brakes are closed (Reset). If the brake is enabled,WaitOneThe desire to charge can only fail, and the toll station is just a false one.

 

Iv. Initial status of AutoResetEvent and ManualResetEvent

SetAutoResetEventAndManualResetEventThe constructor initializes the parking gate status of the toll station:

New Auto/ManualResetEvent (false):The brake is disabled by default;
New Auto/ManualResetEvent (true):The brake is enabled by default.

IfNew Auto/ManualResetEvent (true)That is, if the brake is enabled by default,WaitOneIt doesn't make any sense. The vehicle should pass through again.

See the following code:

Static EventWaitHandle _ tollStation = new AutoResetEvent (true); // static void Main (string [] args) {new Thread (Car1) is enabled by default on the brake ). start (); Console. readKey ();} static void Car1 () {_ tollStation. waitOne (); // because the brake is enabled by default, WaitOne is meaningless and will not stop the vehicle from moving forward to the Console. writeLine ("success! The brakes are open. I have arrived! ");}

Running will print:

Success! The brakes are open. I have arrived!

IfNew AutoResetEvent (true)ChangeNew AutoResetEvent (flase)That is, if the brake is disabled by default, no value will be printed, that is, the vehicle cannot pass.

So how can we pass it? Must be called in the main threadSetThe method is to open the brakes and pass through.

Code:

Static EventWaitHandle _ tollStation = new AutoResetEvent (false); // by default, the gate disables static void Main (string [] args) {new Thread (Car1 ). start (); _ tollStation. set (); // enable the brake Console. readKey ();} static void Car1 () {_ tollStation. waitOne (); // wait for the brake to be enabled, that is, _ event. set (); Console. writeLine ("the brake is enabled. I have arrived! ");}

Running will print:

The brake is turned on. I have arrived!

The code is clear and I will not explain it. In short, when the brake is disabled by defaultSetMethod), the vehicle can pass.

 

5. Use code to describe the features of AutoResetEvent

Code:

Static EventWaitHandle _ tollStation = new AutoResetEvent (false); // by default, the gate disables static void Main (string [] args) {new Thread (Car1 ). start (); // Vehicle 1 new Thread (Car2 ). start (); // vehicle 2_tollstation. set (); Console. readKey ();} static void Car1 () {_ tollStation. waitOne (); // wait for the brake to be enabled, that is, _ tollStation. set (); Console. writeLine ("Vehicle 1, successful pass. ");} Static void Car2 () {_ tollStation. WaitOne (); Console. WriteLine (" Vehicle 2, pass smoothly .! ");}

Running will print:

Vehicle 1, successfully passed.

Although both vehicle 1 and vehicle 2 are running, only vehicle 1 passes smoothly.

Because_ TollStation. Set ()It only runs once, that is, when vehicle 1 passes, the brake is immediately closed, causing vehicle 2 to fail.

Unless it is called again after Vehicle 1 passes_ TollStation. Set ()That is, when the brake is opened again, vehicle 2 can pass:

StaticAutoResetEvent_ TollStation = new AutoResetEvent (false); // by default, the brakes disable static void Main (string [] args) {new Thread (Car1 ). start (); // Vehicle 1 new Thread (Car2 ). start (); // vehicle 2_tollstation. set (); // turn on the brake to allow vehicle 1 to pass through the Console. readKey ();} static void Car1 () {_ tollStation. waitOne (); // wait for the brake to be enabled, that is, _ tollStation. set (); Console. writeLine ("Vehicle 1, successful pass. "); _ TollStation. set (); // re-enable the brake to let vehicle 2 pass} static void Car2 () {_ tollStation. waitOne (); Console. writeLine ("Vehicle 2, successful pass. ");}

Running will print:

Vehicle 1, successfully passed.

Vehicle 2, successfully passed.

That is, each callSet, Only one thread will continue. In other words, how many threads are called?SetThe thread will continue.

This also indicates that,AutoResetEventIs a typical queue operation form.

 

6. Use code to explain the features of ManualResetEvent

In the previous code block,_ TollStation. Set ()After two calls, the two vehicles will pass smoothly.

Is there any way to call it only once?_ TollStation. Set ()Let two or more cars pass smoothly?

The answer is:AutoResetEventChangeManualResetEvent:

Static EventWaitHandle _ tollStation = new ManualResetEvent (false); // change it to ManualResetEvent. By default, the gate disables static void Main (string [] args) {new Thread (Car1 ). start (); // Vehicle 1 new Thread (Car2 ). start (); // vehicle 2_tollstation. set (); // when the brake is enabled, all vehicles will go through the Console. readKey ();} static void Car1 () {_ tollStation. waitOne (); // wait for the brake to be enabled, that is, _ tollStation. set (); Console. writeLine ("Vehicle 1, successful pass. "); // _ TollStation. set (); // no longer needed here} static void Car2 () {_ tollStation. waitOne (); Console. writeLine ("Vehicle 2, successful pass. ");}

Running will print:

Vehicle 1, successfully passed.

Vehicle 2, successfully passed.

This is a good illustration,ManualResetEventThis feature is not automatically disabled when the brakes are enabled. So call once_ TollStation. Set ()All vehicles will pass smoothly.

If the brakes are manually closed at a certain time point, the rear vehicles will not be able to pass. Run the following code:

Static EventWaitHandle _ tollStation = new ManualResetEvent (false); // change it to ManualResetEvent. By default, the gate disables static void Main (string [] args) {new Thread (Car1 ). start (); // Vehicle 1 new Thread (Car2 ). start (); // vehicle 2_tollstation. set (); // turn on the brakes and allow Timer timer = new Timer (CloseDoor, null, 0, 2000); // close the brake Console after 2 seconds. readKey ();} static void Car1 () {_ tollStation. waitOne (); // wait for the brake to be enabled, that is, _ tollStation. set (); Console. writeLine ("Vehicle 1, successful pass . ");} Static void Car2 () {Thread. sleep (3000); // Sleep for 3 seconds _ tollStation. waitOne (); // when you wake up, the brakes are closed. writeLine ("Vehicle 2, successful pass. "); // So the vehicle 2 will not pass} /// <summary> // 2 seconds later, close the gate. /// </summary> static void CloseDoor (object o) {_ tollStation. reset (); // close the brakes}

Running will print:

Vehicle 1, successfully passed.

But the vehicle 2 will not pass, because when the vehicle 2 wakes up, the brake is closed two seconds ago.

 

VII. Summary

1. it looks like,ManualResetEventMore free and open. IfAutoResetEventIf you think it is a zhuqiao that can only be passed by a single userManualResetEventJust like a city gate, you can flood into thousands of troops and horses at once. Of course, you can close the city gate at any time so that the people in the back can't enter it.

2,AutoResetEvent. Set ()=ManualResetEvent. Set ()+ManualResetEvent. Reset ();

3. If only one thread is allowed to use the shared resource separately, you can selectAutoResetEventIf the shared resource allows multiple threads to use at the same time, you can selectManualResetEvent.

4. If you want to control the pause and resume of multiple threads, you can selectManualResetEvent.

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.