深入理解 C# 中的 Semaphore 信号量
Semaphore(信号量)是一种同步原语,用于限制对共享资源或资源池的并发访问线程数量。它通过内部计数器来管理可用资源的数量。
可以将其类比为酒店的房间管理。假设酒店有 3 个房间(初始可用信号量为 3),同时来了 5 位客人。前 3 位客人可以立即入住,而另外 2 位客人则需要在外面等待。当一位客人退房(释放一个信号量)后,等待的客人中便有一位可以入住。这个过程循环往复,始终保持房间(可用信号量)不超过设定的最大数量。
Semaphore 的构造函数接收两个关键参数:initialCount(初始信号量数量)和 maximumCount(最大信号量数量)。它内部维护一个计数器,当线程调用 WaitOne() 时,计数器会减一。当计数器降至零时,后续尝试调用 WaitOne() 的线程将被阻塞,直到有其他线程调用 Release() 释放信号量,计数器增加,被阻塞的线程才得以继续执行。
以下是一个简单的代码示例:
using System;
using System.Threading;
public class SemaphoreDemo
{
// 初始化信号量,允许 2 个线程同时访问,最大容量为 10
private static Semaphore accessLimiter = new Semaphore(2, 10);
public static void Main(string[] args)
{
// 创建三个线程
Thread thread1 = new Thread(Worker) { Name = "WorkerThread-1" };
Thread thread2 = new Thread(Worker) { Name = "WorkerThread-2" };
Thread thread3 = new Thread(Worker) { Name = "WorkerThread-3" };
Thread.Sleep(100); // 稍作延迟
thread1.Start();
thread2.Start();
Thread.Sleep(100); // 再次延迟
thread3.Start();
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
private static void Worker()
{
// 请求获取一个信号量,如果计数器为 0,则在此处阻塞
accessLimiter.WaitOne();
Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' has entered the critical section.");
// 模拟执行一些耗时操作
Thread.Sleep(2000);
Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' is releasing the semaphore.");
// 释放信号量,计数器加一
accessLimiter.Release();
}
}
在上述示例中,由于 accessLimiter 的初始计数是 2,当 thread1 和 thread2 调用 WaitOne() 后,计数器变为 0。此时,thread3 调用 WaitOne() 时会被阻塞。只有当 thread1 或 thread2 调用 Release() 后,thread3 才有机会获得信号量并继续执行。
我们也可以手动释放多个信号量。例如,调用 Release(int releaseCount) 可以一次性释放指定数量的信号量。下面的代码演示了如何通过手动释放信号量来"解救"被阻塞的线程:
using System;
using System.Threading;
public class SemaphoreReleaseDemo
{
// 初始化信号量,允许 2 个线程同时访问,最大容量为 10
private static Semaphore accessLimiter = new Semaphore(2, 10);
public static void Main(string[] args)
{
Thread thread1 = new Thread(Worker) { Name = "WorkerThread-1" };
Thread thread2 = new Thread(Worker) { Name = "WorkerThread-2" };
Thread thread3 = new Thread(Worker) { Name = "WorkerThread-3" };
Thread.Sleep(100);
thread1.Start();
thread2.Start();
thread3.Start(); // thread3 会被阻塞
Thread.Sleep(5000); // 等待一段时间
Console.WriteLine("Main thread releasing 10 semaphores...");
// 手动释放 10 个信号量,确保所有等待的线程都能继续执行
accessLimiter.Release(10);
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
private static void Worker()
{
accessLimiter.WaitOne();
if (Thread.CurrentThread.Name == "WorkerThread-3")
{
Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' was finally unblocked by Release(10).");
}
else
{
Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' has entered the critical section.");
}
// 模拟执行
Thread.Sleep(1000);
Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' is releasing the semaphore.");
accessLimiter.Release();
}
}
Semaphore 继承自 WaitHandle,后者封装了 Windows 底层的同步机制。通过为 Semaphore 指定一个名称,它可以在操作系统层面可见,从而实现进程间的同步。这意味着不同进程中的应用程序可以共享同一个 Semaphore 对象。
以下示例展示了如何创建一个命名的 Semaphore,并从两个独立的应用程序中访问它:
// 应用程序 1 (或进程 1)
using System;
using System.Threading;
public class NamedSemaphoreCreator
{
// 创建一个命名为 "MyNamedSemaphore" 的信号量,初始计数为 3,最大计数为 10
private static Semaphore namedLimiter = new Semaphore(3, 10, "MyNamedSemaphore");
public static void Main(string[] args)
{
Thread threadA = new Thread(ProcessData) { Name = "ProcessThread-A" };
Thread threadB = new Thread(ProcessData) { Name = "ProcessThread-B" };
threadA.Start();
Thread.Sleep(100);
threadB.Start();
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
private static void ProcessData()
{
namedLimiter.WaitOne();
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Thread '{Thread.CurrentThread.Name}' has acquired the named semaphore.");
// 模拟处理
Thread.Sleep(3000);
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Thread '{Thread.CurrentThread.Name}' is releasing the named semaphore.");
namedLimiter.Release();
}
}
// 应用程序 2 (或进程 2) - 访问同一个命名信号量
using System;
using System.Threading;
public class NamedSemaphoreAccessor
{
// 打开已存在的命名信号量
private static Semaphore namedLimiter = Semaphore.OpenExisting("MyNamedSemaphore");
public static void Main(string[] args)
{
Thread threadC = new Thread(ProcessData) { Name = "ProcessThread-C" };
Thread threadD = new Thread(ProcessData) { Name = "ProcessThread-D" };
threadC.Start();
Thread.Sleep(100);
threadD.Start();
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
private static void ProcessData()
{
namedLimiter.WaitOne();
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Thread '{Thread.CurrentThread.Name}' has acquired the named semaphore.");
// 模拟处理
Thread.Sleep(3000);
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] Thread '{Thread.CurrentThread.Name}' is releasing the named semaphore.");
namedLimiter.Release();
}
}
运行上述两个应用程序(可以分别编译并独立执行),您会观察到它们共同遵守由名为 "MyNamedSemaphore" 的信号量设定的访问限制。