Semaphore giới hạn số thread truy cập critical section/resource pool. Namespace: System.Threading.
Constructor chính
| Constructor | Mô tả |
|---|---|
| Semaphore(int initial, int max) | Initial entries, max concurrent |
| Semaphore(int initial, int max, string name) | + named system semaphore |
| Semaphore(int initial, int max, string name, out bool createdNew) | + nhận biết mới tạo |
Ví dụ: Giới hạn 2 thread đồng thời
using System;
using System.Threading;
namespace Program
{
class Demo
{
static Thread[] threads = new Thread[5];
static Semaphore semaphore = new Semaphore(2, 2); // max 2
static void DoSomething()
{
Console.WriteLine("{0} waiting", Thread.CurrentThread.Name);
semaphore.WaitOne(); // Enter
Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
Thread.Sleep(1000); // Work
Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
semaphore.Release(); // Exit
}
static void Main(string[] args)
{
for (int j = 0; j < 5; j++)
{
threads[j] = new Thread(DoSomething);
threads[j].Name = "Thread " + j;
threads[j].Start();
}
Console.Read();
}
}
}
Kết quả (thứ tự có thể khác)
Thread 2 waiting Thread 0 waiting Thread 3 waiting Thread 1 waiting Thread 4 waiting Thread 2 begins! Thread 1 begins! Thread 2 releasing... Thread 1 releasing... Thread 4 begins! Thread 3 begins! Thread 4 releasing... Thread 0 begins! Thread 3 releasing... Thread 0 releasing...
Lưu ý: SemaphoreSlim nhẹ hơn, cho async/await (WaitAsync), dùng cho in-process. Semaphore dùng cho cross-process (named).