0%

CSharp Semaphore 信号量

限制可同时访问某一资源或资源池的线程数

Semaphore sema = new Semaphore(x,y)
x: 线程池中空位数
y: 线程池的总数

WaitOne

阻止当前线程,直到当前线程的WaitHandle 收到信号

Release

退出信号量并返回前一个计数

示例

排队

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System.Threading;
public class Program
{
static Semaphore sema = new Semaphore(5, 5);//线程池中无线程, 最多同时执行5个线程
const int cycleNum = 9;
static void Main(string[] args)
{
for(int i = 0; i < cycleNum; i++)
{
Thread td = new Thread(new ParameterizedThreadStart(testFun));
td.Name = string.Format("{0}",i.ToString());
td.Start(td.Name);
}
Console.ReadKey();
}
public static void testFun(object obj)
{
sema.WaitOne();
Console.WriteLine(obj.ToString() + "进入:" + DateTime.Now.ToString());
Thread.Sleep(2000);
Console.WriteLine(obj.ToString() + "离开:" + DateTime.Now.ToString());
sema.Release();
}
}

Leetcode打印零与奇偶数

输入:n = 5
输出:”0102030405”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Threading;
public class ZeroEvenOdd {
private int n;
public Semaphore semaphore = new Semaphore(1, 1);//奇数偶数打印完解锁
public Semaphore semaphore2 = new Semaphore(0, 1);//0打印完解锁打印奇数
public Semaphore semaphore3 = new Semaphore(0, 1);//0打印完解锁打印偶数

public ZeroEvenOdd(int n) {
this.n = n;
}

// printNumber(x) outputs "x", where x is an integer.
public void Zero(Action<int> printNumber) {
for(int i=0;i<n;i++)
{
semaphore.WaitOne();
printNumber(0);
if(i%2 == 0)
{
semaphore2.Release();
}
else
{
semaphore3.Release();
}

}
}

public void Even(Action<int> printNumber) {
for(int i=2;i<=n;i=i+2)
{
semaphore3.WaitOne();
printNumber(i);
semaphore.Release();
}

}

public void Odd(Action<int> printNumber) {
for(int i=1;i<=n;i=i+2)
{
semaphore2.WaitOne();
printNumber(i);
semaphore.Release();
}
}
}