.NET Frameworkでは結構前のバージョンからSystem.Threading.Semaphoreなるものが使えるようになっている。
例えば次のようなコードだが,Semaphoreをnamespaceに使ってしまったので,System.Threading.Semaphoreをいちいち書いている。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Semaphore
{
class Program
{
private static System.Threading.Semaphore sem;
static void Main(string[] args)
{
sem = new System.Threading.Semaphore(0, 1);
for (int i = 1; i <= 10; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(Worker));
t.Start(i);
}
Thread.Sleep(500);
Console.WriteLine("Main thread calls Release(1).");
sem.Release(1);
Console.WriteLine("Main thread exits.");
}
private static void Worker(object num)
{
Console.WriteLine("Thread {0} started " +
"and waits for the semaphore.", num);
sem.WaitOne();
{
// ここに一スレッドごと実行したい内容
Console.WriteLine("Thread {0} enters the semaphore.", num);
}
Int32 count = sem.Release(1);
Console.WriteLine("Thread {0} releases the semaphore. " +
"The previous semaphore cout: {1}",
num, count);
}
}
}
実はmutexより速いが,lockなどより時間がかかるらしい。

