补充:好的,所以我可以分离互斥锁和信号量,我只想知道我的计数器想法对吗?即Release减一和WaitOne加一,只有当计数器大于零时才允许运行。这个说法对吗?
我有一些运行良好的代码:按顺序运行 first() second() third()。
我只想知道信号量中的计数器是如何工作的?我知道它是计数器。就是说Release减一,WaitOne加一,只有计数器大于零才允许运行。正确的?
但是我读了关于另一件事的书,互斥量,书中说互斥量 Waitone 减一,释放加一,所以互斥量与信号量相反?正确的?
代码:
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); //initialize as start counter 1
}
public void first()
{
Console.WriteLine("First");
s1.Release(); // minus one
}
public void second()
{
s1.WaitOne(); //add one two times
s1.WaitOne();
Console.WriteLine("Second");
s2.Release();
}
public void third()
{
s2.WaitOne(); // add one two times
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);
}
}
}