[英]How does as Mutex relate to a Semaphore?
补充:好的,所以我可以将互斥量和信号量分开,我只想知道我的反主意是对的吗? 即Release减一,而WaitOne加一,只有当计数器大于零时,它才能运行。 这句话对吗?
我有一些运行良好的代码:按顺序运行first()second()third()。
我只想知道信号量计数器的工作原理? 我知道这是对的。 是Release减一,而WaitOne加一,只有当计数器大于零时,它才能运行。 对?
但是我读了另一本书Mutex,这本书说Mutex 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);
}
}
}
互斥锁基本上是信号量的一种特殊情况。 可以想到(即使实际上不会实现)从1开始且永远不能大于1的信号量。
想象一下Semaphore
作为整数的包装,而mutex
作为布尔的包装。 它只有两种状态,空闲或锁定。
Mutex就像只有一个允许线程的信号量。
Mutex仅一次允许访问一个资源,而信号量可以设置为允许任何预设数量的并发访问资源或一段代码。
编辑:
如果它们都被命名,则可以在不同的进程中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.