C#中的信号量
信号量类允许您设置对临界区有访问权限的线程数的限制。此类用于控制对资源池的访问。System.Threading.Semaphore 是信号量的命名空间,因为它包含实现信号量所需的所有方法和属性。
要在 C# 中使用信号量,您只需要实例化一个 Semaphore 对象即可。它至少有两个参数:
参考
—
MSDN
| 序号 | 构造函数和描述 |
|---|---|
| 1 | Semaphore(Int32,Int32) 初始化 Semaphore 类的新实例,指定初始条目数和最大并发条目数。 |
| 2 | Semaphore(Int32,Int32,String) — 初始化 Semaphore 类的新实例,指定初始条目数和最大并发条目数,并可以选择指定系统信号量对象的名称。 |
| 3 | Semaphore(Int32,Int32,String,Boolean) 初始化 Semaphore 类的新实例,指定初始条目数和最大并发条目数,可以选择指定系统信号量对象的名称,并指定一个变量来接收指示是否创建了新的系统信号量的值。 |
让我们来看一个例子
在这里,我们使用了以下 Semaphore 构造函数,该构造函数初始化 Semaphore 类的新实例,指定最大并发条目数,并可以选择预留一些条目。
static Semaphore semaphore = new Semaphore(2, 2);
示例
using System;
using System.Threading;
namespace Program
{
class Demo
{
static Thread[] t = new Thread[5];
static Semaphore semaphore = new Semaphore(2, 2);
static void DoSomething()
{
Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
semaphore.WaitOne();
Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
Thread.Sleep(1000);
Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
semaphore.Release();
}
static void Main(string[] args)
{
for (int j = 0; j < 5; j++)
{
t[j] = new Thread(DoSomething);
t[j].Name = "thread number " + j;
t[j].Start();
}
Console.Read();
}
}
}输出
以下是输出结果
thread number 2 = waiting thread number 0 = waiting thread number 3 = waiting thread number 1 = waiting thread number 4 = waiting thread number 2 begins! thread number 1 begins! thread number 2 releasing... thread number 1 releasing... thread number 4 begins! thread number 3 begins! thread number 4 releasing... thread number 0 begins! thread number 3 releasing... thread number 0 releasing...
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP