1.概述
1.1.使用场景:比如io的访问控制,只有3个端口,当有第4个需要连接的时候,就需要等待,直到有一个io端口释放。
1.2.特点:与互斥类似,只不过信号量可以由多个线程同时使用,比如设置的信号数是2,那就两个线程可以使用,但第3个线程需等待。
2.代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello word");
int threadCount = 6;
//semaphore
// n.信号标,旗语;臂板信号装置; v.打旗语,发信号
int semaphoreCount = 4;
var semaphore = new SemaphoreSlim(semaphoreCount, semaphoreCount);
var thread = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
thread[i] = new Thread(ThreadMain);
thread[i].Start(semaphore);
}
for (int i=0; i< threadCount; i++) {
thread[i].Join();
}
Console.WriteLine("All thread finished");
Console.ReadKey();
}
static void ThreadMain(object o) {
SemaphoreSlim semaphore = o as SemaphoreSlim;
Trace.Assert(semaphore != null, "o must be a SemaphoreSlim type");
bool isCompleted = false;
while (!isCompleted) {
if (semaphore.Wait(600))
{
try
{
Console.WriteLine("Thread {0} locks the semaphore", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
}
finally
{
semaphore.Release();
Console.WriteLine("Thread {0} releases the semphore", Thread.CurrentThread.ManagedThreadId);
isCompleted = true;
}
}
else {
Console.WriteLine("Timeout for thread {0} ", Thread.CurrentThread.ManagedThreadId);
}
}
}
}
}
3 运行效果
4.代码分析