c# Semaphore(信号量)
信號量 Semaphore
類似互斥鎖,但它可以允許多個線程同時訪問一個共享資源
通過使用一個計(jì)數(shù)器來控制對共享資源的訪問,如果計(jì)數(shù)器大于0,就允許訪問,如果等于0,就拒絕訪問。計(jì)數(shù)器累計(jì)的是“許可證”的數(shù)目,為了訪問某個資源。線程必須從信號量獲取一個許可證。
通常在使用信號量時,希望訪問共享資源的線程將嘗試獲取一個許可證,如果信號量的計(jì)數(shù)器大于0,線程將獲取一個許可證并將信號量的計(jì)數(shù)器減1,否則先線程將阻塞,直到獲取一個許可證;當(dāng)線程不再需要共享資源時,將釋放鎖擁有的許可證,并將許可證的數(shù)量加1,如果有其他的線程正在等待許可證,那么該線程將立刻獲取許可證。
另外,允許同時訪問的資源的進(jìn)程數(shù)量是在創(chuàng)建信號量時指定的,如果創(chuàng)建一個允許進(jìn)程訪問的信號量數(shù)目為1,則該信號量就和互斥鎖的用法一樣。
Public Semaphore(int initialCount,int maximumCount)
initialCount指信號量許可證的初始值,maximumCount為最大值
獲取許可證使用WaitOne()
不需要時釋放使用 public int Release();或者public int Release(int? releaseCount);
using System; using System.Collections.Generic; using System.Linq; using System.Text;using System.Threading;namespace MyTTCon {class mythread{public Thread thrd;//創(chuàng)建一個可授權(quán)2個許可證的信號量,且初始值為2static Semaphore sem = new Semaphore(2, 2);public mythread(string name){thrd = new Thread(this.run);thrd.Name = name;thrd.Start();}void run(){Console.WriteLine(thrd.Name + "正在等待一個許可證……");//申請一個許可證sem.WaitOne();Console.WriteLine(thrd.Name + "申請到許可證……");for (int i = 0; i < 4 ; i++){Console.WriteLine(thrd.Name + ": " + i);Thread.Sleep(1000);}Console.WriteLine(thrd.Name + " 釋放許可證……");//釋放sem.Release();}}class mysemaphore{public static void Main(){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();}} }總結(jié)
以上是生活随笔為你收集整理的c# Semaphore(信号量)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: saying可数吗(saying)
- 下一篇: C# WebProxy POST 或者
