# semaphore和mutex的区别？

Mutex 相比信号量增加了所有权的概念，一只锁住的 Mutex 只能由给它上锁的线程解开，只有系铃人才能解铃。Mutex 的功能也就因而限制在了构造临界区上。

『同步』这个词也可以拆开看，一侧是等待数据的『事件』或者『通知』，一侧是保护数据的 『临界区』。信号量可以满足这两个功能，但是可以注意到两个功能的应用场景还是蛮大的，有 do one thing and do it best 的空间。linux 内核曾将 semaphore 作为同步原语，后面代码变得较难维护，刷了一把 mutex 变简单了不少还变快了，需要『通知』 的场景则替换为了 completion variable。semaphore都变成二等公民了

Goodbye semaphores?

Difference between completion variables and semaphores

How are mutexes and semaphores different with respect to their implementation in a Linux kernel?

Some facts on mutex in Linux.
- only one task can hold the mutex at a time
- only the owner can unlock the mutex (unlike the semaphore)
- multiple unlocks are not permitted
- recursive locking is not permitted (since here count can be maximum 1 unlike the semaphore where for e.g count = 5)
- task may not exit with mutex held
- memory areas where held locks reside must not be free
- mutexes may not be used in hardware or software interrupt contexts such as tasklets and timers

A mutex
is essentially the same thing as a binary semaphore and sometimes uses
the same basic implementation. The differences between them are in how
they are used. While a binary semaphore may be used as a mutex, a mutex
is a more specific use-case, in that only the thread that locked the
mutex is supposed to unlock it. This constraint makes it possible to
implement some additional features in mutexes:

1. Since only the thread that locked the mutex is supposed to unlock
it, a mutex may store the id of thread that locked it and verify the
2. Mutexes may provide priority inversion
safety. If the mutex knows who locked it and is supposed to unlock it,
it is possible to promote the priority of that thread whenever a
higher-priority task starts waiting on the mutex.
3. Mutexes may also provide deletion safety, where the thread holding the mutex cannot be accidentally deleted.
4. Alternately, if the thread holding the mutex is deleted (perhaps due
to an unrecoverable error), the mutex can be automatically released.
5. A mutex may be recursive: a thread is allowed to lock it multiple times without causing a deadlock.

mutex，一句话：保护共享资源。

semaphore的用途，一句话：调度线程

mutex是一个厕所一把钥匙，谁抢上钥匙谁用厕所，谁没抢上谁就等着；semaphore是多个同样厕所多把同样的钥匙 ---- 只要你能拿到一把钥匙，你就可以随便找一个空着的厕所进去。

a源自一个线程，b源自另一个线程，计算c = a + b也是一个线程。（即一共三个线程）

int a, b, c;
void geta()
{
a = calculatea();
semaphore_increase();
}

void getb()
{
b = calculateb();
semaphore_increase();
}

void getc()
{
semaphore_decrease();
semaphore_decrease();
c = a + b;
}

// semaphore的机制我在这里就不讲了，百度一下你就知道。
// semaphore_increase对应sem_post
// semaphore_decrease对应sem_wait

semaphore和条件锁的区别：

posted @ 2021-09-30 19:57  Rogn  阅读(214)  评论(0编辑  收藏  举报