pthreads 互斥体 vs 信号量

发布于 2024-08-18 13:54:36 字数 31 浏览 6 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

萌面超妹 2024-08-25 13:54:36

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

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

事实上,您可以用由互斥体同步的 INT 来表示信号量。

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.

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

独﹏钓一江月 2024-08-25 13:54:36

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

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

这适用于使用不同线程代码的线程。 ,它也访问相同的数据并且也被相同的互斥锁锁定。

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

您是否曾经允许另一个线程解锁同一个互斥锁,然后允许已经在互斥锁中等待(阻塞)的线程解除阻塞并访问数据? (希望您明白我在这里所说的内容。)

根据商定的通用定义,

  • 对于“互斥体”,这种情况不会发生。没有其他线程可以解锁该锁
    线程中,
  • 在带有“二进制信号量”的 这种情况可能会发生。任何其他线程都可以解锁
    命中

因此,如果您非常注重使用二进制信号量而不是互斥量,那么您应该非常小心地“确定”锁定和解锁的范围,我的意思是,每个命中每个锁的控制流都应该 解锁调用,也不应该有任何“首次解锁”,而应该始终是“首次锁定”。

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

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

耳根太软 2024-08-25 13:54:36

厕所示例

互斥锁:

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

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

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

信号量:

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

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

来源

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

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.

"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

风筝有风,海豚有海 2024-08-25 13:54:36

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

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

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

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.

断肠人 2024-08-25 13:54:36

这两篇文章详细介绍了 mutex信号量
另外这个堆栈溢出答案也给出了类似的答案。

This two articles explain great details about mutex vs semaphores
Also this stack overflow answer tells the similar answer.

半夏半凉 2024-08-25 13:54:36

信号量互斥体之间的区别就是机制模式之间的区别。区别在于它们的目的(意图)和它们的工作方式(行为)。

互斥体屏障管道并行编程模式互斥体用于(预期)保护关键部分并确保互斥Barrier 使代理(线程/进程)保持相互等待。

mutex 模式的特征(行为)之一是只有允许的代理(进程或线程)才能进入临界区,并且只有该代理可以自愿摆脱这种情况。

在某些情况下,互斥体一次允许单个代理。在某些情况下,它允许多个代理(多个读取器)并不允许某些其他代理(写入器)。

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

在流行文化中,信号量是由内核提供的机制,而互斥体是由用户空间库提供的。

请注意,对于信号量互斥体存在一些误解。它说信号量用于同步。并且互斥体拥有所有权。这是由于流行的操作系统书籍。但事实是所有互斥体、信号量和屏障都用于同步。互斥体的目的不是所有权而是互斥。这种误解导致了流行的面试问题的兴起,询问互斥体和二进制信号量的区别。

总结,

intent

  • 互斥量,互斥
  • 信号量,实现并行设计模式

behavior

  • 互斥量,只有允许的代理进入临界区并且只有它(他们)可以退出
  • 信号量,如果标志说走就进入,否则等到有人改变标志

在设计中从角度来看,互斥锁更像是状态模式,其中状态选择的算法可以改变状态。 binary-semaphore 更像是strategy-pattern,其中外部算法可以改变状态并最终选择运行的算法/策略。

The difference between the semaphore and mutex is the difference between mechanism and pattern. The difference is in their purpose (intent)and how they work(behavioral).

The mutex, barrier, pipeline are parallel programming patterns. Mutex is used(intended) to protect a critical section and ensure mutual exclusion. Barrier makes the agents(thread/process) keep waiting for each other.

One of the feature(behavior) of mutex pattern 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.

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

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

In popular culture, semaphores are mechanisms provided by kernels, and mutexes are provided by user-space library.

Note, there are misconceptions about semaphores and mutexes. It says that semaphores are used for synchronization. And mutexes has 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 ownership but mutual exclusion. This misconception gave the rise of popular interview question asking the difference of the mutexes and binary-semaphores.

Summary,

intent

  • mutex, mutual exclusion
  • semaphore, implement parallel design patterns

behavior

  • 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

In design perspective, mutex is more like state-pattern where the algorithm that is selected by the state can change the state. The binary-semaphore is more like strategy-pattern where the external algorithm can change the state and eventually the algorithm/strategy selected to run.

不忘初心 2024-08-25 13:54:36

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

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.

洒一地阳光 2024-08-25 13:54:36

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

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

逆光下的微笑 2024-08-25 13:54:36

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

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

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

信号量:

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

signal(S) {
      S++;
}

互斥量:

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

release() {
      available = true;
}

Mutex is like sempaphore with with 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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文