Thursday, December 23, 2010

WPF - Thread Synchronization using Barrier

In this post, we will be discussing about a new Thread Signaling construct available in .net 4.0. This signaling construct is Barrier. It basically allows participating threads to work in phases in synchronization. After signaling, the barrier blocks the threads from execution until all participating threads have signaled. As all signals are received, it performs a post-blocking action. As soon as the post-blocking action is finished, all participating threads can resume their operation.

We discussed CountdownEvent in the previous post. It must be remembered that both of these signaling constructs are introduced with .net 4.0. Though CountdownEvent also depends upon signaling of a certain number of threads but it does not block them after they signal until we explicitly call Wait afterwards [http://msdn.microsoft.com/en-us/library/system.threading.countdownevent.wait.aspx]. The other difference is that a thread can only signal once at one time for barrer. Alternatively, CountdownEvent can generate two signals by using overloads of Signal method available.

This seems to be very disciplined construct. The example of this feature should be form an environment which is also very disciplined. Let us take the example of an army mission. A team of 4 army-men are formed to attack an enemy land. The team consists of three soldiers and their commander. Each soldier has to secure a position and signal the commander. When all soldiers have signaled, the commander runs all procedures and orders the attack. In order to keep the example simple, we are discussing this one phase, otherwise, we can also extend this example for other posts in the enemy land. We can also update it to include the provision of reducing the number of participants when a soldier is down.

The form should appear as follows:

Clicking each button should update the display about the ready position of the soldier. When all buttons are clicked, the commander notification text box is udpated as "Attack!!!".

Now look at the definition of barrier, _barrier. Since all signals are received, it can run the post-phase action. In this case, we are just using Thread.Sleep() to simulate any work done by the thread.