线程同步:旗语(Semaphore)
2010-10-14 15:14
197 查看
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个获得锁定的线程之一解除了旗语锁定。 } }
相关文章推荐
- 使用Semaphore(旗语)控制线程同步
- 线程同步:旗语(Semaphore)
- 线程同步的方式——Mutex(互斥量)、 Condition variable(条件变量)和Semaphore(信号量)
- 经典线程同步 信号量Semaphore
- 线程同步----信号量(Semaphore)
- 基元线程同步——内核模式构造(WaitHandle,EventWaitHandle,AutoResetEvent,ManualResetEvent,Semaphore,Mutex)
- C# 线程同步(5)- 信号量 Semaphore
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 线程同步: mutex, semaphore, condition(ZT)[转载]
- 转---秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 进程/线程同步——Critical Section,Mutex,Semaphore,Event区别
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 线程同步之mutex和Semaphore
- 【java并发】线程同步工具Semaphore的使用
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore (续)
- MFC(2)MFC中使用信号量(semaphore)做线程同步——用户启动子线程打开串口
- 【java并发】线程同步工具Semaphore的使用
- 进程/线程同步——Critical Section,Mutex,Semaphore,Event区别