如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !

其實.NET中的信號量(Semaphore)是作業系統維持的一個整數,當整數位0時,其他執行緒無法進入,當整數大于0時,執行緒可以進入,每當一個執行緒進入,整數-1,執行緒退出后整數+1,整數不能超過信號量的最大請求數,信號量在初始化的時候可以指定這個整數的初始值,
System.Threading.Semaphore類的建構式的兩個引數第一個就是信號量的內部整數初始值,也就是初始請求數,第二個引數就是最大請求數,
using System;
using System.Threading;
namespace ConsoleApp3
{
class Program
{
static Semaphore semaphore;
//當前信號量中執行緒數量
static int count;
//用于生成亂數
static Random r;
static void Main()
{
r = new Random();
//初始化信號量:初始請求數為1,最大請求數為3
semaphore = new Semaphore(1, 3);
//放出10個執行緒
for (int i = 0; i < 5; i++)
ThreadPool.QueueUserWorkItem(doo, i + 1);
Console.ReadKey(true);
}
static void doo(object arg)
{
int id = (int)arg;
PrintStatus(id, "等待");
semaphore.WaitOne();
PrintStatus(id, "進入");
PrintCount(1);
Thread.Sleep(r.Next(1000));
PrintStatus(id, "退出");
PrintCount(-1);
semaphore.Release();
}
//輸出執行緒狀態
static void PrintStatus(int id, string s)
{
Console.WriteLine("執行緒{0}:{1}", id, s);
}
//修改并輸出執行緒數量
static void PrintCount(int add)
{
Interlocked.Add(ref count, add);
Console.WriteLine("=> 信號量值:{0}", Interlocked.Exchange(ref count, count));
}
}
}

Semaphore:可理解為允許執行緒執行信號的池子,池子中放入多少個信號就允許多少執行緒同時執行,
private static void MultiThreadSynergicWithSemaphore()
{
//0表示創建Semaphore時,擁有可用信號量數值
//1表示Semaphore中,最多容納信號量數值
Semaphore semaphore = new Semaphore(0, 1);
Thread thread1 = new Thread(() =>
{
//執行緒首先WaitOne等待一個可用的信號量
semaphore.WaitOne();
//在得到信號量后,執行下面代碼內容
Console.WriteLine("thread1 work");
Thread.Sleep(5000);
//執行緒執行完畢,將獲得信號量釋放(還給semaphore)
semaphore.Release();
});
Thread thread2 = new Thread(() =>
{
semaphore.WaitOne();
Console.WriteLine("thread2 work");
Thread.Sleep(5000);
semaphore.Release();
});
thread2.Start();
thread1.Start();
//因在創建Semaphore時擁有的信號量為0
//semaphore.Release(1) 為加入1個信號量到semaphore中
semaphore.Release(1);
}
明:
1、如果semaphore.Release(n),n>semaphore最大容納信號量,將出例外,
2、當semaphore擁有的信號量為1時,Semaphore相當于Mutex
3、當semaphore擁有的信號量>1時,信號量的數量即可供多個執行緒同時獲取的個數,此時可認為獲取到信號量的執行緒將同時執行(實際情況可能與CPU核心數、CPU同時支出執行緒數有關)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/227018.html
標籤:.NET技术
