Multithreading programming learning notes-thread synchronization (2), multithreading programming learning notes

Source: Internet
Author: User

Multithreading programming learning notes-thread synchronization (2), multithreading programming learning notes
Multi-thread programming learning notes-thread synchronization (1) 4. Use AutoResetEvent

1. Use the AutoResetEvent class to send notifications from one thread to another.

2. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; // introduce the thread using System. diagnostics; namespace detail {class Program {static AutoResetEvent autoResetWork = new AutoResetEvent (false); static AutoResetEvent autoResetMain = new AutoResetEvent (false); static void Main (string [] args) {Console. writeLine ("START, AutoResetEvent synchronization"); string t HreadName = "Thread 1"; var t = new Thread () => working (threadName, 10); t. start (); Console. writeLine ("START, First Job"); autoResetWork. waitOne (); // everything is ready for use. The event is stuck here, Console. writeLine ("the first job is finished"); Console. writeLine ("main Thread operation, prepare to send a signal"); Thread. sleep (TimeSpan. fromSeconds (5); // sends a signal, indicating that the value has been written into it. Set is a method for sending signals. AutoResetMain. Set (); Console. WriteLine ("now runs the second job. "); AutoResetWork. waitOne (); Console. writeLine ("second work completed"); Console. read ();} static void working (string name, int seconds) {Console. writeLine ("{0} start running", name); Thread. sleep (TimeSpan. fromSeconds (seconds); Console. writeLine ("{0} is working ...... ", Name); // sends a signal, indicating that the value has been written. Set is a method for sending signals. AutoResetWork. set (); Console. writeLine ("waiting for the main thread to complete the work and sending a signal"); autoResetMain. waitOne (); Console. writeLine ("the main Thread sends a signal to start the second job"); Thread. sleep (TimeSpan. fromSeconds (seconds); Console. writeLine ("{0} the second job is in progress ..... ", Name); autoResetWork. Set ();}}}

3. The program running result, such.

 

In the above program, we define two AutoResetEvent instances. One of them is sending signals to the main thread from the subthread, and the other is sending signals to the subthread from the main thread. When constructing the AutoResetEvent, we pass in false to define the initial status unsignaled of the two instances. In this state, any thread that calls the WaitOne method of the two instances will be blocked until we call the Set method. If true is input during the construction, the initial status of the two instances is singnaled, And the thread calls WaitOne to process it immediately.

 

5. Use the ManualResetEventSlim class

1. Use ManualResetEventSlim to transmit signals between threads.

2. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; // introduce the thread using System. diagnostics; namespace ThreadSynchronousDemo {class Program {static ManualResetEventSlim manuResetWork = new ManualResetEventSlim (false); static void Main (string [] args) {Console. writeLine ("START, ManualResetEventSlim synchronization"); string threadName = "thread 1"; string threadName2 = "thread 2"; string threadName3 = "thread 3 "; var t = new Thread () => working (threadName, 3); var t2 = new Thread () => working (threadName2, 6 ))); var t3 = new Thread () => working (threadName3, 12); t. start (); t2.Start (); t3.Start (); Thread. sleep (TimeSpan. fromSeconds (5); Console. writeLine ("START, open the thread work gate"); manuResetWork. set (); // sends a signal to Thread. sleep (TimeSpan. fromSeconds (3); manuResetWork. reset (); Console. writeLine ("Thread working gate, close"); Thread. sleep (TimeSpan. fromSeconds (10); Console. writeLine ("opened the thread work door for the second time"); manuResetWork. set (); // sends a signal to Thread. sleep (TimeSpan. fromSeconds (3); manuResetWork. reset (); Console. writeLine ("thread working door, closed again"); Console. read ();} static void working (string name, int seconds) {Console. writeLine ("{0} Rest", name); Thread. sleep (TimeSpan. fromSeconds (seconds); Console. writeLine ("{0} waiting to open the door for thread running", name); manuResetWork. wait (); Console. writeLine ("the door for thread running is opened and {0} is working", name );}}}

3. The program running result, such.

When the main program starts, first create an instance of the ManualResetEvenSlim class, and then start three threads, waiting for the event signal to notify them to continue working.

ManualResetEvenSlim works a bit like a crowd passing through a gate, while an AutoResetEvent event is like a revolving door and can only pass by one person at a time.

ManualResetEvenSlim opens the door and remains open until the Reset method is called. Wait until the Set method is called again to open the door.

 

Vi. Use the CountDownEvent class

1. Use the CountDownEvent signal class to wait until a certain number of operations are completed.

2. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; // introduce the thread using System. diagnostics; namespace ThreadSynchronousDemo {class Program {static CountdownEvent CountDownWork = new CountdownEvent (2); static void Main (string [] args) {Console. writeLine ("START, CountdownEvent synchronization"); var t = new Thread () => working ("1st worker Thread Tasks", 3 ))); var t2 = new Thread (( () => Working ("2nd worker Thread Tasks", 6); // var t3 = new Thread ((() => working ("3rd worker thread Tasks", 12); t. start (); t2.Start (); // t3.Start (); Thread. sleep (TimeSpan. fromSeconds (5); Console. writeLine ("START, thread job count"); CountDownWork. wait (); Console. writeLine ("count completed, 2 work completed! "); // If the third thread annotated with the above Code is restored and the object is released, the third thread may throw the CountDownWork error. dispose (); Console. read ();} static void working (string message, int seconds) {Console. writeLine ("rest before work {0}", DateTime. now. second); Thread. sleep (TimeSpan. fromSeconds (seconds); Console. writeLine (message); CountDownWork. signal (); Console. writeLine ("sending a counting signal, one task has been completed ");}}}

3. The program running result is shown in.

When the program starts, A CountDownEven instance is created and specified in the constructor. When the two operations are completed, a signal is given. Then we started two threads for work. When the second thread completes the operation, the main thread will return from the status waiting for CountDownEvent and continue to work. In this scenario, the main thread needs to wait for multiple threads to finish their work before continuing.

Disadvantage: You must wait for a specified number of threads to complete the job. Otherwise, the job will always wait. Make sure that the Signal method is called after all threads finish the job when CountDownEvent is used.

Note:

1) the code of the third thread commented out in the above Code will also encounter the following error in principle.

 

2) If you enable the third thread and annotate CountDownWork. Dispose ();, the following error message is displayed.

 

 

 

 

 

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.