您的位置:首页 > 其它

线程同步:旗语(Semaphore)

2010-11-03 17:35 253 查看



线程同步:旗语(Semaphore) 收藏

view plaincopy to clipboardprint?using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//添加命名空间
using System.Threading;
using System.Diagnostics;

//旗语(Semaphore)锁定非常类似于互斥锁定,其区别是,旗语锁定可以同时由多个线程使用。
//旗语锁定是一种计数的互斥的锁定
//使用旗语锁定,可以定义允许同时访问受旗语访锁定保护的资源的线程个数。如果有许多资源,且只允许一定数量的线程访问该资源,就可以使用旗语锁定
namespace ThreadStudy2
{
class Program
{
static void Main(string[] args)
{
int threadCount = 6;
int semaphoreCount = 4;
//第一参数:最初自由的锁定数,第二参数:锁定数的计数
Semaphore semaphore = new Semaphore(semaphoreCount,semaphoreCount);
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(ThreadMain);
threads[i].Start(semaphore);
}
for (int i = 0; i < threadCount; i++)
{
threads[i].Join();
}
Console.WriteLine("All threads finished");
Console.Read();

}
static void ThreadMain(object o)
{
//线程利用WaitOne()锁定了旗语,旗语锁定的计数是4,所以4个线程可以获得锁定。线程5必须等待,时间为500毫秒。如果在该等待时间后未能获得锁定,线程就把一个信息写入控制台,循环中继续等待
//只要获得锁定,线程就把一个信息写入控制台,睡眠一段时间后,解除锁定,在解除锁定时,一定要解除资源的锁定。
//这就是在finally处理程序中调用Release()方法的原因
Semaphore semaphore = o as Semaphore;
Trace.Assert(semaphore != null, "o must be a Semaphore type");
bool isCompleted = false;
while (!isCompleted)
{
if (semaphore.WaitOne(600, false))
{
try
{
Console.WriteLine("Thread {0} locks the sempahore",Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
}
finally
{
semaphore.Release();
Console.WriteLine("Thread {0} releases the semaphore ",Thread.CurrentThread.ManagedThreadId);
isCompleted = true;
}
}
else
{
Console.WriteLine("Timeout for thread {0} ; wait again", Thread.CurrentThread.ManagedThreadId);
}
}
}
//运行现象:
//4个线程获得了锁定,另外2个线程需要等待,该等待会重复进行,直到4个获得锁定的线程之一解除了旗语锁定。

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: