C: 锁定 pthread mutex 是否会将线程置于 FIFO 队列中?
C: Does locking a pthread mutex place the thread in a FIFO queue?
假设 线程 1 已锁定 mutex
并做了一些工作。
如果 线程 2 调用:
pthread_mutex_lock(&mutex);
然后 线程 3 调用相同的方法:
pthread_mutex_lock(&mutex);
然后 线程 1 解锁 mutex
。 FIFO(先进先出)是否适用于试图锁定 mutex
的线程?
如果是这样,线程 2 将保证是下一个获取 mutex
.
的线程
Does FIFO (First In First Out) apply to the threads trying to lock the mutex?
不,不能保证先进先出。
参见https://man7.org/linux/man-pages/man3/pthread_mutex_lock.3p.html:
If there are threads
blocked on the mutex object referenced by mutex when
pthread_mutex_unlock()
is called, resulting in the mutex becoming
available, the scheduling policy shall determine which thread shall
acquire the mutex.
在 Linux 上,pthread 互斥锁是使用 futex 实现的,pthread_mutex_unlock()
涉及 FUTEX_WAKE
:
No guarantee is provided about which waiters are awoken (e.g.,
a waiter with a higher scheduling priority is not guaranteed
to be awoken in preference to a waiter with a lower priority).
这确实取决于现行的调度策略。如果它是 SCHED_FIFO,那么对于每个优先级,确实有一个等待者的 fifo 列表,而且 futexes 确实考虑到了这一点(参见 futexes,第 FUTEX_LOCK_PI 节)。 SCHED_FIFO 往往是用于实时应用程序的策略。
上的页面
假设 线程 1 已锁定 mutex
并做了一些工作。
如果 线程 2 调用:
pthread_mutex_lock(&mutex);
然后 线程 3 调用相同的方法:
pthread_mutex_lock(&mutex);
然后 线程 1 解锁 mutex
。 FIFO(先进先出)是否适用于试图锁定 mutex
的线程?
如果是这样,线程 2 将保证是下一个获取 mutex
.
Does FIFO (First In First Out) apply to the threads trying to lock the mutex?
不,不能保证先进先出。
参见https://man7.org/linux/man-pages/man3/pthread_mutex_lock.3p.html:
If there are threads blocked on the mutex object referenced by mutex when
pthread_mutex_unlock()
is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.
在 Linux 上,pthread 互斥锁是使用 futex 实现的,pthread_mutex_unlock()
涉及 FUTEX_WAKE
:
No guarantee is provided about which waiters are awoken (e.g., a waiter with a higher scheduling priority is not guaranteed to be awoken in preference to a waiter with a lower priority).
这确实取决于现行的调度策略。如果它是 SCHED_FIFO,那么对于每个优先级,确实有一个等待者的 fifo 列表,而且 futexes 确实考虑到了这一点(参见 futexes,第 FUTEX_LOCK_PI 节)。 SCHED_FIFO 往往是用于实时应用程序的策略。
上的页面