C # Thread Rendezvous instance

Source: Internet
Author: User

There is a topic: Four threads T1,t2,t3,t4, write data to 4 files, requires: T1 can only write "1", T2 can only write "2", T3 can only write "3", T4 can write "4", 4 files A,b,c,d write the following content:

    • A:123412341234 .....
    • b:234123412341 ....
    • c:341234123412 ....
    • D:412341234123 ....

Simple analysis, for a file, T1 write "1", we want to notify T2 to write "2", and T1 to D file waiting to write "1", and so on.

1. Implementation by waiting handle

Obviously can be implemented with a wait handle, notify T2 to write "2" equivalent to call the Set method on a wait handle, waiting on the D file to write "1" equivalent to another wait handle called the WaitOne method, the bottom is the use of 4 AutoResetEvent to implement it:

classprogram{Private StaticList<streamwriter>_sws; Private StaticList<autoresetevent>_WHS;

Private Static voidMain (string[] args) { varFileNames =Newlist<string> {"A","B","C","D"}; //Create or empty a fileFilenames.foreach (name = { if(!file.exists (name)) File.create (name); Else { using(varSW =NewStreamWriter (name)) SW. Write (""); } }); _sws=Filenames.select (File.appendtext). ToList (); //Create a wait handle for each file write_WHS = Filenames.select (name =NewAutoResetEvent (false)). ToList (); //Create and start 4 threads to perform a task varThreads =NewList<thread> { NewThread (() = Work (1)),NewThread (() = Work (2)),NewThread (() = Work (3)),NewThread (() = Work (4)) }; Threads. ForEach (t=T.start ()); //wait for thread to end and close StreamwriteThreads. ForEach (t =T.join ()); Console.WriteLine ("Mission Accomplished! "); _sws. ForEach (SW=SW. Close ()); } Static voidWork (intThreadindex) { varNext = Threadindex-1; //to allow the program to end, print it 100 times. for(inti =0; I < -; i++) { varWH =_whs[next]; varSW =_sws[next]; Lock(SW) {SW. Write (Threadindex); } Next= (Next-1) <0?3: Next-1; Waithandle.signalandwait (WH, _whs[next]); //signals on the WH and waits for execution on the next wait handle } }}

In the example above, we created 4 threads to print 1,2,3,4 separately, and 4 wait handles were created for each file's write to signal communication. The last main thread closes the file stream after waiting for all threads to end. To allow the program to end normally, only 100 loops are written in the work method.

Take T1 (the first thread in the list) as an example, after printing 1 in a file, call waithandle.signalandwait (Wh,wh[next]), that is, signal notification on the WH can then be written, and wait for the write signal on the next wait handle.

Refer to the Thread in C # or the corresponding Chinese translation for sinalandwait .

2. Using the Barrier class to achieve

In addition to waiting for a handle to achieve the problem, the same can be done through wait and Pulse . If it is a version of the framework 4.0 or higher, it is easier to implement this problem through the Barrier class (which is based on Wait/pulse and spin locks).

classprogram{Private StaticBarrier _barrier; Private Static voidMain (string[] args) {        varFileNames =Newlist<string> {"A","B","C","D" }; //Create or empty a fileFilenames.foreach (name =        {            if(!file.exists (name))            File.create (name); Else            {                using(varSW =NewStreamWriter (name)) SW. Write ("");                }        }); //The thread that _barrier on the signalandwait will be blocked until this method is called 4 times_barrier =NewBarrier (4); _sws=Filenames.select (File.appendtext).        ToList (); //Create and start 4 threads to perform a task        varThreads =NewList<thread> {            NewThread (() = Work (1)),NewThread (() = Work (2)),NewThread (() = Work (3)),NewThread (() = Work (4))        }; Threads. ForEach (t=T.start ()); //wait for thread to end and close StreamwriteThreads. ForEach (t =T.join ()); Console.WriteLine ("Mission Accomplished! "); _sws. ForEach (SW=SW.    Close ()); }    Static voidWork (intThreadindex) {        varNext = Threadindex-1;  for(inti =0; I < -; i++)        {            varSW =_sws[next]; Lock(SW) {SW.            Write (Threadindex); } _barrier.            SignalAndWait (); Next= (Next-1) <0?3: Next-1; }    }}

A Barrier class is used to replace the 4 wait handles, and the thread calls signalandwait and blocks until the method is called 4 times. In this example, it means that 4 threads are always printing synchronously, which explains the Barrier class well:

For the Barrier class, refer to the Thread in C # or the corresponding Chinese translation.

C # Thread Rendezvous instance

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.