When a "set of tasks" is required to run a series of stages in parallel, but each phase waits for all of his tasks to begin before the completion of the previous phase, this type of collaboration can be synchronized by barrier instances.
After the barrier is initialized, it waits for a certain number of signals to arrive, which is specified when the barrier is initialized, and after the specified number of signals has arrived, barrier executes a specified action, which is also specified at barrier initialization. Barrier will reset after the action is executed, and will wait for a certain number of signals to arrive before performing the specified action. The signal is sent through the member function signalandwait (), the task that executes the signalandwait () function, or the thread will wait, barrier will wait for a certain number of signals to arrive, and then barrier be reset after executing the specified action. The task or thread where the signalandwait () function is located will continue to run. In the process of running the program, you can increase or decrease the number of signals that need to wait through the member functions AddParticipant () and Removeparticpant ()
1 Public Static voidPHASE1 (inttaskId)2 {3Console.WriteLine ($"Task[{taskid}] Complete Phase1");4 }5 Public Static voidPhase2 (inttaskId)6 {7Console.WriteLine ($"Task[{taskid}] Complete Phase2");8 }9 Public Static voidPHASE3 (inttaskId)Ten { OneConsole.WriteLine ($"Task[{taskid}] complete Phase3"); A } - Public Static voidPhase4 (inttaskId) - { theConsole.WriteLine ($"Task[{taskid}] Complete Phase4"); - } - Static voidMain (string[] args) - { +Barrier Barrier =NewBarrier (3); - intTaskId =0; + for(inti =0; I <3; i++) A { atTask.Factory.StartNew (() = - { - intCur = interlocked.increment (reftaskId); - Phase1 (cur); - barrier. SignalAndWait (); - Phase2 (cur); in barrier. SignalAndWait (); - Phase3 (cur); to barrier. SignalAndWait (); + Phase4 (cur); - barrier. SignalAndWait (); the }); * } $ Console.readkey ();Panax Notoginseng}
Barrier Example
The task execution process is as follows:
Execution Result:
TASK1/TASK2/TASK3 will execute Phase2 after Phase1 is executed.
Barrier Code Implementation Analysis: Https://www.cnblogs.com/majiang/p/7898027.html
[. NET multithreading] Barrier