线程同步:旗语(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个获得锁定的线程之一解除了旗语锁定。
}
}
相关文章推荐
- 使用Semaphore(旗语)控制线程同步
- 线程同步:旗语(Semaphore)
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- C# 线程同步 信号量 Semaphore
- 重新想象 Windows 8 Store Apps (47) - 多线程之线程同步: Semaphore, CountdownEvent, Barrier, ManualResetEvent, AutoResetEvent
- 多线程7:经典线程同步 信号量Semaphore
- 多线程之Semaphore实现线程同步
- 线程同步互斥之信号量对象(Semaphore)
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- C#线程同步(5)- 信号量 Semaphore
- 秒杀多线程第八篇 经典线程同步 信号量 Semaphore
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 基元线程同步构造之信号量(Semaphore)
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- Java Semaphore 生产者消费者线程同步
- linux系统编程:线程同步-信号量(semaphore)
- 重新想象 Windows 8 Store Apps (47) - 多线程之线程同步: Semaphore, CountdownEvent, Barrier, ManualResetEvent, AutoResetEvent
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- GDC dispatch_semaphore 信号量 协调线程同步