C#高級編程學習時的小例子:
public void main()
{
int threadCount = 6;
int semaphoreCount = 3;
var semaphore = new SemaphoreSlim(semaphoreCount,
semaphoreCount);
var threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(threadMain);
threads[i].Start(semaphore);
}
for (int i = 0; i < threadCount; i++)
{
threads[i].Join();
}
Console.WriteLine("All threads Finished");
}
public void threadMain(object o)
{
SemaphoreSlim semaphore = o as SemaphoreSlim;
Trace.Assert(semaphore != null, "o must be a Semaphore type");
bool isCompleted = false;
while(!isCompleted)
{
if (semaphore.Wait(600))
{
try
{
Console.WriteLine("Thread {0} locks the semaphore",
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
}
finally
{
semaphore.Release();
Console.WriteLine("Thread {0} releases the semaphore",
Thread.CurrentThread.ManagedThreadId);
isCompleted = true;
}
}
else
{
Console.WriteLine("TimeOut for Thread {0};Wait again",
Thread.CurrentThread.ManagedThreadId);
}
}
}
結果: