using System;
using System.Threading;
public class Example
{
private static Semaphore _pool;
private static int _padding;
public static void Main()
{
_pool = new Semaphore(0, 3);
for (int i = 1; i <= 5; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(Worker));
t.Start(i);
}
Thread.Sleep(500);
Console.WriteLine("Main thread calls Release(3).");
_pool.Release(3);
Console.ReadKey();
}
private static void Worker(object num)
{
Console.WriteLine("Thread {0} begins " +
"and waits for the semaphore.", num);
_pool.WaitOne();
int padding = Interlocked.Add(ref _padding, 100);
Console.WriteLine("Thread {0} enters the semaphore.", num);
Thread.Sleep(1000 + padding);
Console.WriteLine("Thread {0} releases the semaphore.", num);
Console.WriteLine("Thread {0} previous semaphore count: {1}",
num, _pool.Release());
}
}
信号量:Semaphore:Release
最新推荐文章于 2025-04-30 15:36:35 发布
本文通过C#示例代码展示了如何使用Semaphore类来控制多个线程的并发访问。具体实现中,创建了一个Semaphore实例限制同时运行的线程数,并通过WaitOne和Release方法确保线程按指定数量依次执行。
8551

被折叠的 条评论
为什么被折叠?



