I'm trying to understand how to use semaphores while working with threads.
I have 2 threads that uses the same resource - an ArrayList
.
One method adds a random temperature to the list, the other method calculate the average temperature of the list.
How do I use semaphore's methods Wait
and Release
in this context?
and how can I control that my thread that calculate the average temperature starts after something is added to my list.
This is some of my code:
class Temperature
{
private static Random random = new Random();
private static ArrayList buffer = new ArrayList();
static SemaphoreSlim e, b;
public static void Main (string[] args)
{
e = new SemaphoreSlim(6); //how will this work?
b = new SemaphoreSlim(1);
Thread t1 = new Thread (Add);
t1.Start ();
Thread t2 = new Thread (Average);
t2.Start ();
}
public static void Add()
{
int temperature;
for (int i=0; i<50; i++)
{
temperature = random.Next (36, 42);
Console.WriteLine ("Temperature added to buffer: " + temperature);
b.Wait ();
e.Wait ();
buffer.Add(temperature);
b.Release ();
Thread.Sleep (50);
}
}
}