信号量是怎么记数的?
我一直以为 Release 记数-1 WaitOne +1 如果 ==0 可以运行 >0不让运行 难道不对么?
/*
MultiThread.Semaphore.test();
*/
using System;
namespace Algorithm.MultiThread
{
class Semaphore
{
System.Threading.Semaphore s1, s2;
public Semaphore()
{
s1 = new System.Threading.Semaphore(1, 5);
s2 = new System.Threading.Semaphore(1, 5); //2个都初始化为1
}
public void first()
{
Console.WriteLine("First");
s1.Release(); // 一次-1
}
public void second()
{
s1.WaitOne(); //2次+1
s1.WaitOne();
Console.WriteLine("Second");
s2.Release();
}
public void third()
{
s2.WaitOne(); //2次+1
s2.WaitOne();
Console.WriteLine("Third");
}
public void startnum(object obj)
{
int i = (int)obj;
switch (i)
{
case 1:
first();
break;
case 2:
second();
break;
case 3:
third();
break;
default:
break;
}
}
public static void test()
{
Semaphore s = new Semaphore();
System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(s.startnum));
System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(s.startnum));
System.Threading.Thread t3 = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(s.startnum));
t1.Start(3);
t2.Start(2);
t3.Start(1);
}
}
}
上代码没问题的 可以先执行first 然后second third.
就是不明白2个信号量初始化都1 无论哪个先执行 waitone 2次都加2了。。。但是只有在first运行后才release -1
所以
我认为 应该是Release +1 WaitOne -1 只有大于0才可以运行
对比一下Mutex 那俩是相反的对吧
每WaitOne()一次计数+1,每ReleaseMutex()一次计数-1 --------------------编程问答-------------------- 没人知道么
没人知道么
没人知道么
没人知道么
补充:.NET技术 , C#