Linux pthreads 互斥量与信号量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2065747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:41:02  来源:igfitidea点击:

pthreads mutex vs semaphore

clinuxsynchronizationpthreadsmutex

提问by cppdev

What is the difference between semaphores and mutex provided by pthread library ?

pthread 库提供的信号量和互斥量有什么区别?

采纳答案by Hassan Syed

semaphores have a synchronized counter and mutex's are just binary (true / false).

信号量有一个同步计数器,互斥量只是二进制的(真/假)。

A semaphore is often used as a definitive mechanism for answering how many elements of a resource are in use -- e.g., an object that represents n worker threads might use a semaphore to count how many worker threads are available.

信号量通常用作回答资源的多少元素正在使用的明确机制——例如,表示 n 个工作线程的对象可能使用信号量来计算有多少工作线程可用。

Truth is you can represent a semaphore by an INT that is synchronized by a mutex.

事实是,您可以通过互斥锁同步的 INT 来表示信号量。

回答by C Learner

mutex is used to avoid race condition between multiple threads.

互斥用于避免多线程之间的竞争条件。

whereas semaphore is used as synchronizing element used across multiple process.

而信号量用作跨多个进程使用的同步元素。

mutex can't be replaced with binary semaphore since, one process waits for semaphore while other process releases semaphore. In case mutex both acquisition and release is handled by same.

互斥量不能用二进制信号量替换,因为一个进程等待信号量而其他进程释放信号量。如果互斥,获取和释放都由相同的处理。

回答by batteringRam

Mutexes can be applied only to threads in a single process and do not work between processes as do semaphores.

互斥体只能应用于单个进程中的线程,而不能像信号量那样在进程之间工作。

回答by tsenapathy

This two articles explain great details about mutexvs semaphoresAlso thisstack overflow answer tells the similar answer.

这两篇文章解释这很详细互斥VS信号灯堆栈溢出的答案告诉了类似的答案。

回答by Paxi

I am going to talk about Mutex vs Binary-Semaphore. You obviously use mutex to prevent data in one thread from being accessed by another thread at the same time.

我将讨论互斥量与二进制信号量。您显然使用互斥锁来防止一个线程中的数据同时被另一个线程访问。

(Assume that you have just called lock() and in the process of accessing a 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.)

(假设您刚刚调用了 lock() 并且在访问数据的过程中。这意味着,您不希望任何其他线程(或同一线程代码的另一个实例)访问由相同的互斥锁。也就是说,如果在不同的线程实例上执行相同的线程代码,则锁定了锁,则 lock() 应该阻塞控制流。)

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).

在这种情况下,您仍在访问数据的过程中,并且您可能需要另外 15 秒才能到达互斥锁解锁(以便在互斥锁中被阻塞的另一个线程将解锁并允许控制访问数据)。

Do you ever allow 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,

根据商定的通用定义,

  • with “mutex” this can't happen. No other thread can unlock the lock in your thread
  • with “binary-semaphore” this can happen. Any other thread can unlock the lock in your thread
  • 使用“互斥锁”就不会发生这种情况。没有其他线程可以解锁您线程中的锁
  • 使用“二进制信号量”可能会发生这种情况。任何其他线程都可以解锁您线程中的锁

So, if you are very particular about using binary-semaphore instead of mutex, then you should be very careful in “scoping” the locks and unlocks, I mean, that every control-flow that hits every lock should hit an unlock call and also there shouldn't be any “first unlock”, rather it should be always “first lock”.

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

回答by ajinkya

Semaphore is more used as flag, for which your really don't need to bring RTOS / OS. Semaphore can be accidentally or deliberately changed by other threads (say due to bad coding). When you thread use mutex, it owns the resources. No other thread can ever access it, before resource get free.

信号量更多地用作标志,您真的不需要带 RTOS / OS。信号量可能会被其他线程意外或故意更改(例如由于错误的编码)。当您线程使用互斥锁时,它拥有资源。在资源释放之前,没有其他线程可以访问它。

回答by shuva

The difference between the semaphoreand mutexis the difference between mechanismand pattern. The difference is in their purpose (intent)and how they work(behavioral).

之间的差semaphoremutex之间的差别的机制图案。区别在于它们的目的(意图)和它们的工作方式(行为)。

The mutex, barrier, pipelineare parallel programming patterns. Mutexis used(intended) to protect a critical sectionand ensure mutual exclusion. Barriermakes the agents(thread/process) keep waiting for each other.

mutexbarrierpipeline并行编程模式Mutex用于(打算)保护 acritical section并确保mutual exclusion. Barrier使代理(线程/进程)保持相互等待。

One of the feature(behavior) of mutexpattern is that only allowed agent(s)(process or thread) can enter a critical section and only that agent(s) can voluntarily get out of that.

模式的特征(行为)之一mutex是只有被允许的代理(进程或线程)才能进入临界区,并且只有该代理才能自愿退出。

There are cases when mutexallows single agent at a time. There are cases where it allows multiple agents(multiple readers) and disallow some other agents(writers).

有些情况下一次mutex允许单个代理。在某些情况下,它允许多个代理(多个读者)而不允许其他一些代理(作者)。

The semaphoreis a mechanismthat can be used(intended) to implement different patterns. It is(behavior) generally a flag(possibly protected by mutual exclusion). (One interesting fact is even mutexpattern can be used to implement semaphore).

semaphore是一种机制,可用于(意图)来实现不同的图案。它是(行为)通常是一个标志(可能受互斥保护)。(一个有趣的事实是甚mutex至可以使用模式来实现信号量)。

In popular culture, semaphoresare mechanisms provided by kernels, and mutexesare provided by user-space library.

在流行文化中,semaphores是内核提供的机制,mutexes由用户空间库提供。

Note, there are misconceptions about semaphoresand mutexes. It says that semaphoresare used for synchronization. And mutexeshas ownership. This is due to popular OS books. But the truth is all the mutexes, semaphores and barriers are used for synchronization. The intent of mutex is not ownershipbut mutual exclusion. This misconception gave the rise of popular interview question asking the difference of the mutexesand binary-semaphores.

请注意,对semaphores和存在误解mutexes。它说semaphores用于synchronization. 并且mutexesownership。这是由于流行的操作系统书籍。但事实是所有的互斥锁、信号量和屏障都用于同步。互斥锁的意图不是ownership但是mutual exclusion。这种误解了流行的面试问题的询问的区别崛起mutexesbinary-semaphores

Summary,

概括,

意图
  • mutex, mutual exclusion
  • semaphore, implement parallel design patterns
  • 互斥,互斥
  • 信号量,实现并行设计模式
行为
  • mutex, only the allowed agent(s) enters critical section and only it(they) can exit
  • semaphore, enter if the flag says go, otherwise wait until someone changes the flag
  • 互斥锁,只有被允许的代理才能进入临界区,只有它(他们)才能退出
  • 信号量,如果标志说go,则进入,否则等待有人更改标志

In design perspective, mutexis more like state-patternwhere the algorithm that is selected by the state can change the state. The binary-semaphoreis more like strategy-patternwhere the external algorithmcan change the state and eventually the algorithm/strategy selected to run.

从设计的角度来看,mutex更像state-pattern是状态选择的算法可以改变状态的地方。这binary-semaphore更像strategy-pattern外部算法可以改变状态并最终选择运行的算法/策略。

回答by Ankur

The Toilet Example

厕所示例

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.

是厕所的钥匙。一个人可以拥有钥匙——占用厕所——当时。完成后,此人将钥匙交给(释放)队列中的下一个人。

"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."

“互斥锁通常用于序列化对不能由多个线程同时执行的可重入代码段的访问。互斥锁对象只允许一个线程进入受控段,迫使其他线程尝试访问该段等到第一个线程从该部分退出。”

(A mutex is really a semaphore with value 1.)

(互斥锁实际上是一个值为 1 的信号量。)

Semaphore:

信号:

Is the number of free identical toilet keys. For 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.

是免费的相同厕所钥匙的数量。例如,假设我们有四个带有相同锁和钥匙的马桶。信号量计数 - 钥匙的数量 - 开始时设置为 4(所有四个厕所都是免费的),然后随着人们进来,计数值递减。如果所有厕所都满了,即。没有剩余的空闲键,信号量计数为 0。现在,当 eq。一个人离开厕所,信号量增加到1(一个空闲键),并给队列中的下一个人。

"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)."

“信号量将共享资源的同时用户数量限制为最大数量。线程可以请求访问资源(递减信号量),并可以发出信号表示它们已完成使用资源(递增信号量)。”

Source

来源

回答by Ava

Mutex is like sempaphore with with S=1.

互斥体就像 S=1 的信号量。

You can control number of concurrent accesses with semaphore but with mutex only one process at a time can access it.

您可以使用信号量控制并发访问的数量,但使用互斥锁一次只能有一个进程可以访问它。

See the implemenation of these two below: (all functions are atomic)

请参阅下面这两个的实现:(所有功能都是原子的)

Semaphore:

信号:

wait(S) {
      while (S <= 0 )
         ; // busy wait
      S--;
}

signal(S) {
      S++;
}

Mutex:

互斥体:

acquire() {
      while (!available)
            ; // busy wait
      available = false;
}

release() {
      available = true;
}