I thought the following code would run all 10 threads, two at a time, and then print "done" after being Release()called 10 times. But this is not what happened:
int count = 0;
Semaphore s = new Semaphore(2, 2);
for (int x = 0; x < 10; x++)
{
Thread t = new Thread(new ThreadStart(delegate()
{
s.WaitOne();
Thread.Sleep(1000);
Interlocked.Increment(ref count);
s.Release();
}));
t.Start(x);
}
WaitHandle.WaitAll(new WaitHandle[] { s });
Console.WriteLine("done: {0}", count);
output:
done: 6
If the only way to implement the functionality that I'm looking for is to pass EventWaitHandleto each thread and then make WaitAll()an array of these EventWaitHandles, then what does the value WaitAll()on the array mean only a semaphore? In other words, when is an unlock of a waiting thread?
source
share