using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading;
/*
* 标题:如何使用信号量的示例代码
* Author:kagula
* Date:2015-6-16
* Environment:VS2010SP1, .NET Framework 4 client profile, C#.
* Note:[1]“信号量”可以看成是“授权(证)池”。
* 一个授权(证)池内有零个或多个授权(证)。
* [2]下面的示例sem of Semaphore相当于最多只能有一个授权(证)的授权池。
* [3]每调用一次sem.Release添加一个授权(证)。
* 连接调用多次sem.Release导致超出授权池所能容纳的授权(证)数量,会抛出异常。
* [4]每调用一次sem.WaitOne就使用一个授权(证)。
* */
namespace
kagula
{
class
mySemaphore
{
//第一个参数,代表当前授权次数。
// 0表示没有授权(证)。
//第二个参数,代表Semaphore实例最多能容纳几个授权证。
// 1表示最大授权次数为1次。
// 超出允许的授权次数,比如说sem.Release连续调用了两次,会抛出异常。
public
static
Semaphore sem =
new
Semaphore(0, 1);
public
static
void
Main()
{
//添加一次授权。
//释放一个sem.WaitOne()的阻塞。
sem.Release();
myThread mythrd1 =
new
myThread(
"Thrd #1"
);
myThread mythrd2 =
new
myThread(
"Thrd #2"
);
myThread mythrd3 =
new
myThread(
"Thrd #3"
);
myThread mythrd4 =
new
myThread(
"Thrd #4"
);
mythrd1.thrd.Join();
mythrd2.thrd.Join();
mythrd3.thrd.Join();
mythrd4.thrd.Join();
//input any key to continue...
Console.ReadKey();
}
//end main function
}
//end main class
class
myThread
{
public
Thread thrd;
public
myThread(
string
name)
{
thrd =
new
Thread(
this
.run);
thrd.Name = name;
thrd.Start();
}
void
run()
{
Console.WriteLine(thrd.Name +
"正在等待一个许可(证)……"
);
//如果不加参数会导致无限等待。
if
(mySemaphore.sem.WaitOne(1000))
{
Console.WriteLine(thrd.Name +
"申请到许可(证)……"
);
Thread.Sleep(500);
//虽然下面添加了许可,但是,其它线程可能没拿到许可,超时退出了。
Console.WriteLine(thrd.Name +
"添加一个许可(证)……"
);
mySemaphore.sem.Release();
}
else
{
Console.WriteLine(thrd.Name +
" 超时(等了一段时间还是没拿到许可(证))退出……"
);
}
}
}
//end class
}
//end namespace
联系客服