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


互斥锁只能由获得它的线程释放。 二进制信号量可以由任何线程(或进程)发出信号。

因此,信号量更适合于一些同步问题,如生产者-消费者。

在Windows上,二进制信号量更像事件对象而不是互斥对象。


答案可能取决于目标操作系统。例如,我所熟悉的至少一个RTOS实现允许对单个OS互斥量进行多个连续的“get”操作,只要它们都来自同一个线程上下文中。在允许另一个线程获得互斥量之前,多个get必须被相等数量的put替换。这与二进制信号量不同,对于二进制信号量,无论线程上下文如何,一次只允许一个get。

这种互斥锁背后的思想是,通过一次只允许一个上下文修改数据来保护对象。即使线程获得了互斥量,然后调用进一步修改对象的函数(并在自己的操作周围获得/放置保护互斥量),这些操作仍然应该是安全的,因为它们都发生在单个线程下。

{
    mutexGet();  // Other threads can no longer get the mutex.

    // Make changes to the protected object.
    // ...

    objectModify();  // Also gets/puts the mutex.  Only allowed from this thread context.

    // Make more changes to the protected object.
    // ...

    mutexPut();  // Finally allows other threads to get the mutex.
}

当然,在使用此特性时,必须确保单个线程中的所有访问都是安全的!

我不确定这种方法有多普遍,或者它是否适用于我所熟悉的系统之外。有关这种互斥锁的示例,请参阅ThreadX RTOS。


它们不是一回事。它们有不同的用途! 虽然这两种类型的信号量都有一个满/空状态,并且使用相同的API,但它们的用法非常不同。

互斥信号量 互斥信号量用于保护共享资源(数据结构、文件等)。

互斥信号量由接收它的任务“拥有”。如果Task B尝试semGive一个当前由Task a持有的互斥锁,Task B的调用将返回一个错误并失败。

互斥对象总是使用以下顺序:

  - SemTake
  - Critical Section
  - SemGive

这里有一个简单的例子:

  Thread A                     Thread B
   Take Mutex
     access data
     ...                        Take Mutex  <== Will block
     ...
   Give Mutex                     access data  <== Unblocks
                                  ...
                                Give Mutex

二进制信号量 二进制信号量解决了一个完全不同的问题:

任务B被挂起等待某些事情发生(例如传感器被绊倒)。 传感器跳闸和中断服务程序运行。它需要通知任务的行程。 任务B应运行并对传感器跳闸采取适当的操作。然后继续等待。


   Task A                      Task B
   ...                         Take BinSemaphore   <== wait for something
   Do Something Noteworthy
   Give BinSemaphore           do something    <== unblocks

注意,对于二进制信号量,B获取信号量,a给出信号量是可以的。 同样,二进制信号量不能保护资源不被访问。信号量的给予和获取从根本上是分离的。 对于同一个任务来说,对同一个二进制信号量的给予和获取通常没有什么意义。


它们的同步语义非常不同:

互斥对象允许对给定资源的序列化访问,即多个线程等待一个锁,一次一个,正如前面所说,线程拥有锁,直到锁完成:只有这个特定的线程可以解锁它。 二进制信号量是一个值为0和1的计数器:任务阻塞在它上,直到任何任务执行sem_post。信号量宣布资源可用,并提供等待机制,直到发出可用信号。

因此,可以将互斥锁视为在任务之间传递的令牌,将信号量视为交通红灯(它向某人发出信号,表示可以继续进行)。


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

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


互斥锁用于阻塞关键区域,而信号量用于计数。


在理论层面上,它们在语义上并无不同。您可以使用信号量实现互斥量,反之亦然(参见这里的示例)。在实践中,实现是不同的,它们提供的服务也略有不同。

实际的区别(就围绕它们的系统服务而言)在于互斥锁的实现旨在成为一种更轻量级的同步机制。在oracle语言中,互斥锁被称为锁存器,而信号量被称为等待。

在最低级别,他们使用某种原子测试和设置机制。它读取内存位置的当前值,计算某种条件,并在一条不能中断的指令中写入该位置的值。这意味着您可以获得一个互斥锁,并测试是否有人在您之前拥有它。

典型的互斥量实现有一个进程或线程执行test-and-set指令,并评估是否有其他东西设置了互斥量。这里的关键点是与调度程序没有交互,因此我们不知道(也不关心)谁设置了锁。然后,我们要么放弃我们的时间片,并在任务重新调度时再次尝试它,要么执行自旋锁。自旋锁是这样一种算法:

Count down from 5000:
     i. Execute the test-and-set instruction
    ii. If the mutex is clear, we have acquired it in the previous instruction 
        so we can exit the loop
   iii. When we get to zero, give up our time slice.

当我们完成执行受保护的代码(称为临界区)时,我们只需将互斥量的值设置为零或其他表示“清除”的值。如果有多个任务试图获取互斥量,那么下一个计划在互斥量释放后的任务将获得对资源的访问权。通常情况下,您可以使用互斥来控制同步资源,在这种资源中,只需要在很短的时间内对其进行独占访问,通常是对共享数据结构进行更新。

A semaphore is a synchronised data structure (typically using a mutex) that has a count and some system call wrappers that interact with the scheduler in a bit more depth than the mutex libraries would. Semaphores are incremented and decremented and used to block tasks until something else is ready. See Producer/Consumer Problem for a simple example of this. Semaphores are initialised to some value - a binary semaphore is just a special case where the semaphore is initialised to 1. Posting to a semaphore has the effect of waking up a waiting process.

一个基本的信号量算法如下所示:

(somewhere in the program startup)
Initialise the semaphore to its start-up value.

Acquiring a semaphore
   i. (synchronised) Attempt to decrement the semaphore value
  ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.

Posting a semaphore
   i. (synchronised) Increment the semaphore value
  ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable.  
 iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.

在二进制信号量的情况下,两者之间的主要实际区别是围绕实际数据结构的系统服务的性质。

编辑:正如evan正确地指出的那样,自旋锁会降低单个处理器的速度。你只能在多处理器上使用自旋锁,因为在单处理器上,持有互斥锁的进程永远不会在另一个任务运行时重置它。自旋锁只在多处理器架构上有用。


厕所的例子是一个有趣的类比:

Mutex: Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue. Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library (A mutex is really a semaphore with value 1.) Semaphore: Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue. Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library


关于这个主题的好文章:

互斥量与信号量——第1部分:信号量 互斥量与信号量——第2部分:互斥量 互斥量与信号量——第3部分(最后一部分):互斥问题

来自第二部分:

The mutex is similar to the principles of the binary semaphore with one significant difference: the principle of ownership. Ownership is the simple concept that when a task locks (acquires) a mutex only it can unlock (release) it. If a task tries to unlock a mutex it hasn’t locked (thus doesn’t own) then an error condition is encountered and, most importantly, the mutex is not unlocked. If the mutual exclusion object doesn't have ownership then, irrelevant of what it is called, it is not a mutex.


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

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

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

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


除了互斥对象有一个所有者之外,这两个对象还可以针对不同的用途进行优化。互斥锁被设计为只保留很短的时间;违反这一点会导致糟糕的性能和不公平的调度。例如,一个正在运行的线程可能被允许获取一个互斥量,即使另一个线程已经被阻塞在这个线程上。信号量可以提供更多的公平性,或者可以使用几个条件变量强制实现公平性。


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

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

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

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


在窗口,差异如下所示。 MUTEX:成功执行等待的进程必须执行一个信号,反之亦然。二进制信号量:不同的进程可以在一个信号量上执行等待或信号操作。


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


http://www.geeksforgeeks.org/archives/9102将详细讨论。

互斥是一种锁机制,用于同步对资源的访问。 信号量是一种信号机制。

如果他/她想使用二进制信号量来代替互斥量,这取决于程序员。


You obviously use mutex to lock a data in one thread getting accessed by another thread at the same time. Assume that you have just called lock() and in the process of accessing data. This means that you don’t expect any other thread (or another instance of the same thread-code) to access the same data locked by the same mutex. That is, if it is the same thread-code getting executed on a different thread instance, hits the lock, then the lock() should block the control flow there. This applies to a thread that uses a different thread-code, which is also accessing the same data and which is also locked by the same mutex. In this case, you are still in the process of accessing the data and you may take, say, another 15 secs to reach the mutex unlock (so that the other thread that is getting blocked in mutex lock would unblock and would allow the control to access the data). Do you at any cost allow yet another thread to just unlock the same mutex, and in turn, allow the thread that is already waiting (blocking) in the mutex lock to unblock and access the data? Hope you got what I am saying here? As per, agreed upon universal definition!,

使用“互斥”就不会发生这种情况。没有其他线程可以解锁锁 在你的帖子里 使用“二进制信号量”可以实现这种情况。任何其他线程都可以解锁 线程中的锁

因此,如果您非常注重使用二进制信号量而不是互斥量,那么在锁定和解锁的“作用域”时应该非常小心。我的意思是,每个触及每个锁的控制流都应该触及一个解锁调用,也不应该有任何“第一次解锁”,而应该总是“第一次锁定”。


Mutex is used to protect the sensitive code and data, semaphore is used to synchronization.You also can have practical use with protect the sensitive code, but there might be a risk that release the protection by the other thread by operation V.So The main difference between bi-semaphore and mutex is the ownership.For instance by toilet , Mutex is like that one can enter the toilet and lock the door, no one else can enter until the man get out, bi-semaphore is like that one can enter the toilet and lock the door, but someone else could enter by asking the administrator to open the door, it's ridiculous.


互斥锁用于“锁定机制”。每次只有一个进程可以使用共享资源

信号量用于“信号机制” 比如“我完成了,现在可以继续了”


在看了上面的帖子后,这个概念对我来说很清楚。但仍有一些挥之不去的问题。所以,我写了一小段代码。

当我们试图给出一个信号量而不接收它时,它就会通过。但是,当你试图给出一个互斥量而不获取它时,它会失败。我在Windows平台上进行了测试。启用USE_MUTEX使用MUTEX运行相同的代码。

#include <stdio.h>
#include <windows.h>
#define xUSE_MUTEX 1
#define MAX_SEM_COUNT 1

DWORD WINAPI Thread_no_1( LPVOID lpParam );
DWORD WINAPI Thread_no_2( LPVOID lpParam );

HANDLE Handle_Of_Thread_1 = 0;
HANDLE Handle_Of_Thread_2 = 0;
int Data_Of_Thread_1 = 1;
int Data_Of_Thread_2 = 2;
HANDLE ghMutex = NULL;
HANDLE ghSemaphore = NULL;


int main(void)
{

#ifdef USE_MUTEX
    ghMutex = CreateMutex( NULL, FALSE, NULL);
    if (ghMutex  == NULL) 
    {
        printf("CreateMutex error: %d\n", GetLastError());
        return 1;
    }
#else
    // Create a semaphore with initial and max counts of MAX_SEM_COUNT
    ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
    if (ghSemaphore == NULL) 
    {
        printf("CreateSemaphore error: %d\n", GetLastError());
        return 1;
    }
#endif
    // Create thread 1.
    Handle_Of_Thread_1 = CreateThread( NULL, 0,Thread_no_1, &Data_Of_Thread_1, 0, NULL);  
    if ( Handle_Of_Thread_1 == NULL)
    {
        printf("Create first thread problem \n");
        return 1;
    }

    /* sleep for 5 seconds **/
    Sleep(5 * 1000);

    /*Create thread 2 */
    Handle_Of_Thread_2 = CreateThread( NULL, 0,Thread_no_2, &Data_Of_Thread_2, 0, NULL);  
    if ( Handle_Of_Thread_2 == NULL)
    {
        printf("Create second thread problem \n");
        return 1;
    }

    // Sleep for 20 seconds
    Sleep(20 * 1000);

    printf("Out of the program \n");
    return 0;
}


int my_critical_section_code(HANDLE thread_handle)
{

#ifdef USE_MUTEX
    if(thread_handle == Handle_Of_Thread_1)
    {
        /* get the lock */
        WaitForSingleObject(ghMutex, INFINITE);
        printf("Thread 1 holding the mutex \n");
    }
#else
    /* get the semaphore */
    if(thread_handle == Handle_Of_Thread_1)
    {
        WaitForSingleObject(ghSemaphore, INFINITE);
        printf("Thread 1 holding semaphore \n");
    }
#endif

    if(thread_handle == Handle_Of_Thread_1)
    {
        /* sleep for 10 seconds */
        Sleep(10 * 1000);
#ifdef USE_MUTEX
        printf("Thread 1 about to release mutex \n");
#else
        printf("Thread 1 about to release semaphore \n");
#endif
    }
    else
    {
        /* sleep for 3 secconds */
        Sleep(3 * 1000);
    }

#ifdef USE_MUTEX
    /* release the lock*/
    if(!ReleaseMutex(ghMutex))
    {
        printf("Release Mutex error in thread %d: error # %d\n", (thread_handle == Handle_Of_Thread_1 ? 1:2),GetLastError());
    }
#else
    if (!ReleaseSemaphore(ghSemaphore,1,NULL) )      
    {
        printf("ReleaseSemaphore error in thread %d: error # %d\n",(thread_handle == Handle_Of_Thread_1 ? 1:2), GetLastError());
    }
#endif

    return 0;
}

DWORD WINAPI Thread_no_1( LPVOID lpParam ) 
{ 
    my_critical_section_code(Handle_Of_Thread_1);
    return 0;
}


DWORD WINAPI Thread_no_2( LPVOID lpParam ) 
{
    my_critical_section_code(Handle_Of_Thread_2);
    return 0;
}

信号量允许您发出“使用资源完成”的信号,即使它从未拥有该资源,这一事实使我认为在信号量的情况下,拥有和发出信号之间存在非常松散的耦合。


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

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/


神话:

一些文章说“二进制信号量和互斥量是相同的”或“值为1的信号量是互斥量”,但基本的区别是互斥量只能由获得它的线程释放,而你可以从任何其他线程发出信号量

重点:

一个线程可以获得多个锁(互斥锁)。

只有递归互斥锁才能被锁多次,这里的锁和锁应该是一样的

•如果一个线程已经锁定了一个互斥锁,试图再次锁定互斥锁,它将进入该互斥锁的等待列表,这将导致死锁。

二进制信号量和互斥量相似但不相同。

互斥是昂贵的操作,因为与它相关的保护协议。

互斥的主要目的是实现对资源的原子访问或锁定


虽然互斥量和信号量被用作同步原语,但它们之间有很大的区别。 在互斥锁的情况下,只有锁定或获得互斥锁的线程才能解锁它。 在信号量的情况下,等待信号量的线程可以由另一个线程发出信号。 一些操作系统支持在进程之间使用互斥量和信号量。通常使用是在共享内存中创建的。


二进制信号量和互斥量的区别: 所有权: 信号量甚至可以从非当前所有者发出信号(发布)。这意味着您可以简单地从任何其他线程发布,尽管您不是所有者。

信号量是进程中的公共属性,它可以简单地由非所有者线程发布。 请用粗体字标出这个区别,这意味着很多。


互斥量和二进制信号量是相同的用法,但实际上,它们是不同的。

对于互斥锁,只有锁定了它的线程才能解锁它。如果有其他线程来锁定它,它将等待。

对于信号电话来说,情况就不是这样了。信号量没有与特定的线程ID绑定。


以上几乎所有人都说对了。如果有人还有疑问,让我来澄清一下。

互斥->用于序列化 信号- >同步。

两者的目的是不同的,但是,通过精心的编程,可以实现相同的功能。

标准示例->生产者消费者问题。

initial value of SemaVar=0

Producer                           Consumer
---                                SemaWait()->decrement SemaVar   
produce data
---
SemaSignal SemaVar or SemaVar++  --->consumer unblocks as SemVar is 1 now.

希望我能澄清。


正如这里许多人提到的,互斥锁用于保护关键代码段(又名临界段)。你将在同一个线程中获得互斥锁(lock),进入临界区,释放互斥锁(unlock)。

在使用信号量时,您可以让一个线程(例如线程a)等待一个信号量,直到另一个线程(例如线程B)完成任何任务,然后为线程a设置信号量以停止等待,并继续其任务。


虽然二进制信号量可以用作互斥量,但互斥量是一个更具体的用例,因为只有锁定了互斥量的进程才应该解锁它。这种所有权限制使我们有可能对以下情况提供保护:

意外释放 递归死锁 任务死亡死锁

这些限制并不总是存在,因为它们降低了速度。在代码开发期间,您可以暂时启用这些检查。

例如,你可以在互斥锁中启用错误检查属性。错误检查互斥量返回EDEADLK,如果你试图锁定同一个互斥量两次,如果你解锁了一个不是你的互斥量,返回EPERM。

pthread_mutex_t mutex;
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
pthread_mutex_init (&mutex, &attr);

一旦初始化,我们可以将这些检查放在我们的代码中,就像这样:

if(pthread_mutex_unlock(&mutex)==EPERM)
 printf("Unlock failed:Mutex not owned by this thread\n");

互斥锁:假设我们有临界区线程T1想要访问它,然后按照以下步骤进行。 T1:

锁 使用临界区 解锁

二进制信号量:它基于信号等待和信号工作。 等待将“s”的值减少1,通常“s”的值初始化为值“1”, 信号(s)使“s”值加1。如果“s”值为1表示没有人在使用临界区,当“s”值为0时表示临界区正在使用。 假设线程T2正在使用临界区,那么它遵循以下步骤。 T2:

Wait (s)//最初的s值是1,调用Wait后,它的值减少了1,即0 利用临界区 信号(s) //现在s值增加,变成1

Main difference between Mutex and Binary semaphore is in Mutext if thread lock the critical section then it has to unlock critical section no other thread can unlock it, but in case of Binary semaphore if one thread locks critical section using wait(s) function then value of s become "0" and no one can access it until value of "s" become 1 but suppose some other thread calls signal(s) then value of "s" become 1 and it allows other function to use critical section. hence in Binary semaphore thread doesn't have ownership.


“二进制信号量”是一种编程语言规避使用«信号量»,如«互斥量»。显然有两个非常大的区别:

你称呼他们的方式。 标识符的最大长度。


The basic issue is concurrency. There is more than one flow of control. Think about two processes using a shared memory. Now only one process can access the shared memory at a time. If more than one process accesses the shared memory at a time, the contents of shared memory would get corrupted. It is like a railroad track. Only one train can run on it, else there would be an accident.So there is a signalling mechanism, which a driver checks. If the signal is green, the train can go and if it is red it has to wait to use the track. Similarly in case of shared memory, there is a binary semaphore. If the semaphore is 1, a process acquires it (makes it 0) and goes ahead and accesses it. If the semaphore is 0, the process waits. The functionality the binary semaphore has to provide is mutual exclusion (or mutex, in short) so that only one of the many concurrent entities (process or thread) mutually excludes others. It is a plus that we have counting semaphores, which help in synchronizing multiple instances of a resource.

互斥是信号量提供的基本功能。现在在线程上下文中,我们可能有不同的名称和语法。但基本概念是相同的:如何在并发编程中保持代码和数据的完整性。在我看来,像所有权和相关检查这样的东西是由实现提供的改进。


最好的解决方案

唯一的区别是

1.互斥锁-> lock和unlock属于锁定互斥锁的线程。

2.信号量->没有所有权,即;如果一个线程调用semwait(s),任何其他线程都可以调用sempost(s)来移除锁。


互斥锁

Until recently, the only sleeping lock in the kernel was the semaphore. Most users of semaphores instantiated a semaphore with a count of one and treated them as a mutual exclusion lock—a sleeping version of the spin-lock. Unfortunately, semaphores are rather generic and do not impose any usage constraints. This makes them useful for managing exclusive access in obscure situations, such as complicated dances between the kernel and userspace. But it also means that simpler locking is harder to do, and the lack of enforced rules makes any sort of automated debugging or constraint enforcement impossible. Seeking a simpler sleeping lock, the kernel developers introduced the mutex.Yes, as you are now accustomed to, that is a confusing name. Let’s clarify.The term “mutex” is a generic name to refer to any sleeping lock that enforces mutual exclusion, such as a semaphore with a usage count of one. In recent Linux kernels, the proper noun “mutex” is now also a specific type of sleeping lock that implements mutual exclusion.That is, a mutex is a mutex.

互斥锁的简单性和效率来自于它在信号量要求之外强加给用户的附加约束。信号量是按照Dijkstra的原始设计来实现最基本的行为,而互斥锁则不同,它的用例更严格、更窄: n一次只能有一个任务持有互斥锁。也就是说,互斥锁的使用计数总是1。

Whoever locked a mutex must unlock it. That is, you cannot lock a mutex in one context and then unlock it in another. This means that the mutex isn’t suitable for more complicated synchronizations between kernel and user-space. Most use cases, however, cleanly lock and unlock from the same context. Recursive locks and unlocks are not allowed. That is, you cannot recursively acquire the same mutex, and you cannot unlock an unlocked mutex. A process cannot exit while holding a mutex. A mutex cannot be acquired by an interrupt handler or bottom half, even with mutex_trylock(). A mutex can be managed only via the official API: It must be initialized via the methods described in this section and cannot be copied, hand initialized, or reinitialized.

[1] Linux内核开发,第三版Robert Love


I think most of the answers here were confusing especially those saying that mutex can be released only by the process that holds it but semaphore can be signaled by ay process. The above line is kind of vague in terms of semaphore. To understand we should know that there are two kinds of semaphore one is called counting semaphore and the other is called a binary semaphore. In counting semaphore handles access to n number of resources where n can be defined before the use. Each semaphore has a count variable, which keeps the count of the number of resources in use, initially, it is set to n. Each process that wishes to uses a resource performs a wait() operation on the semaphore (thereby decrementing the count). When a process releases a resource, it performs a release() operation (incrementing the count). When the count becomes 0, all the resources are being used. After that, the process waits until the count becomes more than 0. Now here is the catch only the process that holds the resource can increase the count no other process can increase the count only the processes holding a resource can increase the count and the process waiting for the semaphore again checks and when it sees the resource available it decreases the count again. So in terms of binary semaphore, only the process holding the semaphore can increase the count, and count remains zero until it stops using the semaphore and increases the count and other process gets the chance to access the semaphore.

二进制信号量和互斥量之间的主要区别在于,信号量是一种信号机制,而互斥量是一种锁定机制,但二进制信号量的功能似乎与互斥量类似,这造成了混乱,但两者是适用于不同类型工作的不同概念。


你可以通过以下方法清楚地记住不同之处:

互斥锁:用于保护关键区域, 互斥锁不能跨进程使用,只能在单个进程中使用 信号量:用于信号资源的可用性。 信号量既可以跨进程使用,也可以跨进程使用。


互斥量是任何想要解决临界区问题的算法都必须遵循的标准,而二进制信号量本身是一个可以取0和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.

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