23 November 2011

Barrier: synchronizes threads in freamwork 4

Question:

How to build a barrier like a a traffic light for threads and synchronize them?

Solution:

That's what brought us to the barrier of framework 4!



I built code that gets three threads and trying to sync.
There are three types of situations:
1. Green - do not get their delayed and continue normal (driving).
2. Yellow - paused for a second and then goes through the green.
3. Red - delayed for 2 seconds and then goes through the yellow color.


The following code shows a good example of a barrier. Sync object is a barrier. It causes delay by type situation. Join activates the trigger of the action (TrafficLightsAction).

using System;
using
 System.Collections.Generic;
using
 System.Linq;
using
 System.Text;
using
 System.Threading;
using
 System.Threading.Tasks;
namespace
 BarrierTrafficLights
{
     class Program

     {
         static Barrier sync;
         static void Main(string[] args)
         {
             sync = new Barrier(participantCount: 3);
             var Car1 = new Thread( () =>
             {
                 TrafficLightsAction("Car 1 (green light source)"colorTrafficLights.green, true);
             });
             Car1.Start();
             var Car2 = new Thread(() =>
             {
                 TrafficLightsAction("Car 2 (yellow light source)"colorTrafficLights.yellow, true);
             });
             Car2.Start();
             var Car3 = new Thread(() =>
             {
                 TrafficLightsAction("Car3 (red light source)"colorTrafficLights.red, true);
             });
             Car3.Start();


             Car1.Join();
             Car2.Join();
             Car3.Join();

             sync.Dispose();
             Console.ReadKey();
         }
         static void TrafficLightsAction(string name, colorTrafficLights color, bool firstTime)
         {
             if (firstTime)
                 Console.WriteLine("{0} has reached the intersection with traffic lights", name, color);
             switch (color)
             {
                 case colorTrafficLights.green:
                     Console.WriteLine("{0} drove a green light", name);
                     break;
                 case colorTrafficLights.yellow:
                     Console.WriteLine("{0} is at a yellow light ", name);
                     Thread.Sleep(1);
                     TrafficLightsAction(name, colorTrafficLights.green, false);
                     break;
                 case colorTrafficLights.red:
                     Console.WriteLine("{0} is at a red light ", name);
                     Thread.Sleep(2);
                     TrafficLightsAction(name, colorTrafficLights.yellow, false);
                     break;
             }
             sync.SignalAndWait();
         }
     }
     enum colorTrafficLights

     {
         green, yellow, red
     }
}

Hope you understood,
Roi

No comments:

Post a Comment