110,539
社区成员
发帖
与我相关
我的任务
分享
class 网吧
{
Semaphore 容量信号;
ManualResetEvent 关门信号;
WaitHandle[] 多种信号;
public 网吧(int 最大容量 = 5)
{
容量信号 = new Semaphore(0, 最大容量);
关门信号 = new ManualResetEvent(false);
多种信号 = new WaitHandle[] { 容量信号, 关门信号 };
}
public void 上网(bool 死等 = false)
{
int i = WaitHandle.WaitAny(多种信号, 死等 ? Timeout.Infinite : 0);
if (i == 1)
{
Console.WriteLine("网吧关门赶人了");
return;
}
else if (i == WaitHandle.WaitTimeout)
{
Console.WriteLine("网吧当场没有空位");
return;
}
try
{
Console.WriteLine("上网");
Thread.Sleep(10 * 1000);
}
finally
{
Console.WriteLine("下网,让出位置");
容量信号.Release();
}
}
public void 关门()
{
关门信号.Set();
}
}
static Semaphore _semaphore = null;
static bool bSanle = false;
public void init()
{
...
_semaphore = new Semaphore(computerCount, computerCount + 1);
...
}
public void DouSanLeBa()
{
...
bSanle = true;
_sempahore.Release();
...
}
public void ShangWang()
{
_semaphore.WaitOne();
if (bSanle)
{
return;
}
...
}
static bool bQuit = false;
public void Close()
{
Sempahore.Release(nCount);
bQuit = true;
}
public void DoWork()
{
Sempahore.WaitOne();
if (bQuit)
{
return;
}
...
}