二进制信号量和互斥量之间有区别吗?或者它们本质上是相同的?


当前回答

既然上面的答案都不能消除困惑,这里有一个答案可以消除我的困惑。

Strictly speaking, a mutex is a locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there will be ownership associated with mutex, and only the owner can release the lock (mutex). Semaphore is signaling mechanism (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as one task) on your mobile and at the same time your friend called you, an interrupt will be triggered upon which an interrupt service routine (ISR) will signal the call processing task to wakeup.

来源:http://www.geeksforgeeks.org/mutex-vs-semaphore/

其他回答

在Windows上,互斥量和二进制信号量之间有两个区别:

互斥锁只能由拥有所有权的线程释放,即之前调用Wait函数的线程(或在创建互斥锁时获得所有权的线程)。任何线程都可以释放信号量。 线程可以在互斥锁上重复调用等待函数而不会阻塞。但是,如果你在一个二进制信号量上调用了两次等待函数,而中间没有释放信号量,线程就会阻塞。

修改问题是-互斥量和“二进制”信号量在“Linux”中的区别是什么?

答:以下是它们的区别 i)作用域——互斥锁的作用域在创建它的进程地址空间内,用于线程同步。而信号量可以跨进程空间使用,因此它可以用于进程间同步。

ii)互斥量是轻量级的,比信号量更快。Futex甚至更快。

iii)同一线程可以成功多次获得互斥锁,条件是互斥锁释放次数相同。其他线程试图获取将阻塞。而对于信号量,如果同一个进程试图再次获取它,它会阻塞,因为它只能获得一次。

互斥锁控制对单个共享资源的访问。它提供了获取()对资源的访问并在完成后释放()资源的操作。

信号量控制对共享资源池的访问。它提供Wait()操作,直到池中的一个资源可用,并提供Signal()操作,当它返回池时。

当一个信号量保护的资源数量大于1时,它被称为计数信号量。当它控制一个资源时,它被称为布尔信号量。布尔信号量相当于互斥量。

因此,信号量是比互斥量更高级别的抽象。互斥锁可以用信号量来实现,但不能用信号量来实现。

Mutex uses a locking mechanism i.e. if a process wants to use a resource then it locks the resource, uses it and then release it. But on the other hand, semaphore uses a signalling mechanism where wait() and signal() methods are used to show if a process is releasing a resource or taking a resource. A mutex is an object but semaphore is an integer variable. In semaphore, we have wait() and signal() functions. But in mutex, there is no such function. A mutex object allows multiple process threads to access a single shared resource but only one at a time. On the other hand, semaphore allows multiple process threads to access the finite instance of the resource until available. In mutex, the lock can be acquired and released by the same process at a time. But the value of the semaphore variable can be modified by any process that needs some resource but only one process can change the value at a time.

一本有用的书,我从这里学习和复制

互斥对象有所有权,不像信号量。尽管在互斥量范围内的任何线程都可以获得一个未锁定的互斥量,并锁定对同一关键代码段的访问,但只有锁定了互斥量的线程才应该解锁它。