说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C14-SharedMemory/other_syncs.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
14.3.3. Other Synchronization Constructs
互斥锁和信号量并不是多线程程序中仅有的同步结构。在本小节中,我们简要讨论屏障和条件变量这两种同步结构,它们都是 Pthreads 库的一部分。
Mutexes and semaphores are not the only example of synchronization constructs that can be used in the context of multithreaded programs. In this subsection we will briefly discuss the barrier and condition variable synchronization constructs, which are both part of the Pthreads library.
屏障
Barriers
屏障(barrier)是一种同步结构,它强制所有线程到达执行中的一个公共点,然后再放行这些线程继续并发执行。Pthreads 提供了屏障同步原语。要使用 Pthreads 屏障,需要做以下几件事:
A barrier is a type of synchronization construct that forces all threads to reach a common point in execution before releasing the threads to continue executing concurrently. Pthreads offers a barrier synchronization primitive. To use Pthreads barriers, it is necessary to do the following:
- 声明一个屏障全局变量(例如
pthread_barrier_t barrier)
- Declare a barrier global variable (e.g.,
pthread_barrier_t barrier)
- 在
main中初始化屏障(pthread_barrier_init(&barrier))
- Initialize the barrier in
main(pthread_barrier_init(&barrier))
译注
pthread_barrier_init 实际上有三个参数:屏障的地址、属性(通常为 NULL)以及必须到达屏障的线程数,例如 pthread_barrier_init(&barrier, NULL, nthreads)。另外,macOS 没有实现 POSIX 屏障:译者在 Mac 上编译使用 pthread_barrier_t 的代码,Clang 报错「unknown type name ‘pthread_barrier_t’」。在 Mac 上可以用本节后面介绍的「条件变量 + 广播」自己实现屏障,或者在 Linux 中运行这个例子。
- 使用后在
main中销毁屏障(pthread_barrier_destroy(&barrier))
- Destroy the barrier in
mainafter use (pthread_barrier_destroy(&barrier))
- 用
pthread_barrier_wait函数创建一个同步点。
- Use the
pthread_barrier_waitfunction to create a synchronization point.
下面的程序展示了在一个名为 threadEx 的函数中使用屏障:
The following program shows the use of a barrier in a function called
threadEx:
1 | void *threadEx(void *args){ |
在这个例子中,在每个线程都打印出它们开始工作的消息之前,没有哪个线程能开始处理分配给它的那部分数组。如果没有屏障,就可能出现一个线程在其他线程打印出开始工作的消息之前就已经完成了工作!注意,仍然可能出现一个线程在另一个线程完成之前就打印出它已完成工作的情况。
In this example, no thread can start processing its assigned portion of the array until every thread has printed out the message that they are starting work. Without the barrier, it is possible for one thread to have finished work before the other threads have printed their starting work message! Notice that it is still possible for one thread to print that it is done doing work before another thread finishes.
条件变量
Condition Variables
条件变量(condition variable)强制线程阻塞,直到达到某个特定的条件。在线程做某些工作之前必须满足某个条件的场景中,这种结构很有用。如果没有条件变量,线程就不得不反复检查条件是否满足,持续占用 CPU。条件变量总是与互斥锁一起使用。在这种同步结构中,互斥锁实施互斥,而条件变量确保在线程获得互斥锁之前满足特定的条件。
Condition variables force a thread to block until a particular condition is reached. This construct is useful for scenarios in which a condition must be met before the thread does some work. In the absence of condition variables, a thread would have to repeatedly check to see whether the condition is met, continuously utilizing the CPU. Condition variables are always used in conjunction with a mutex. In this type of synchronization construct, the mutex enforces mutual exclusion, whereas the condition variable ensures that particular conditions are met before a thread acquires the mutex.
POSIX 条件变量的类型是 pthread_cond_t。与互斥锁和屏障结构一样,条件变量必须在使用前初始化,在使用后销毁。
POSIX condition variables have the type
pthread_cond_t. Like the mutex and barrier constructs, condition variables must be initialized prior to use and destroyed after use.
要初始化条件变量,使用 pthread_cond_init 函数。要销毁条件变量,使用 pthread_cond_destroy 函数。
To initialize a condition variable, use the
pthread_cond_initfunction. To destroy a condition variable, use thepthread_cond_destroyfunction.
使用条件变量时,常调用的两个函数是 pthread_cond_wait 和 pthread_cond_signal。这两个函数除了需要条件变量的地址之外,还需要一个互斥锁的地址:
The two functions commonly invoked when using condition variables are
pthread_cond_waitandpthread_cond_signal. Both functions require the address of a mutex in addition to the address of the condition variable:
pthread_cond_wait(&cond, &mutex)函数接收条件变量cond和互斥锁mutex的地址作为参数。它使调用线程阻塞在条件变量cond上,直到另一个线程向它发出信号(即「唤醒」它)。
- The
pthread_cond_wait(&cond, &mutex)function takes the addresses of a condition variablecondand a mutexmutexas its arguments. It causes the calling thread to block on the condition variableconduntil another thread signals it (or “wakes” it up).
译注 · wait 会暂时释放互斥锁
上一段说两个函数都需要互斥锁,其实只有 pthread_cond_wait 需要;pthread_cond_signal(&cond) 只接收条件变量(下一条也是这么写的)。调用 pthread_cond_wait 时,调用线程必须已经持有 mutex;按 POSIX 手册,该函数会原子地释放 mutex 并让调用线程阻塞在 cond 上,被唤醒、成功返回时,mutex 又会被调用线程重新持有。正因为等待期间锁被释放了,其他线程(例如下面例子中的「母鸡」)才能获得锁去修改共享变量。pthread_cond_wait(3p)
pthread_cond_signal(&cond)函数使调用线程解除另一个等待在条件变量cond上的线程的阻塞(即向它发出信号)(依据调度优先级)。如果当前没有线程阻塞在该条件上,这个函数就没有任何作用。与pthread_cond_wait不同,无论调用pthread_cond_signal的线程是否持有调用pthread_cond_wait时使用的那个互斥锁,都可以调用这个函数。
- The
pthread_cond_signal(&cond)function causes the calling thread to unblock (or signal) another thread that is waiting on the condition variablecond(based on scheduling priority). If no threads are currently blocked on the condition, then the function has no effect. Unlikepthread_cond_wait, thepthread_cond_signalfunction can be called by a thread regardless of whether or not it owns the mutex in whichpthread_cond_waitis called.
条件变量示例
Condition Variable Example
传统上,当一部分线程在等待另一组线程完成某个动作时,条件变量最为有用。在下面的例子中,我们用多个线程模拟一群农夫从一群母鸡那里收集鸡蛋。「Chicken」(母鸡)和「Farmer」(农夫)代表两类不同的线程。这个程序的完整源代码可以下载(layeggs.c)。注意,为简洁起见,清单中省略了许多注释和错误处理。
Traditionally, condition variables are most useful when a subset of threads are waiting on another set to complete some action. In the following example, we use multiple threads to simulate a set of farmers collecting eggs from a set of chickens. “Chicken” and “Farmer” represent two separate classes of threads. The full source of this program can be downloaded ( layeggs.c). Note that the listing excludes many comments/error handling for brevity.
main 函数创建了一个共享变量 num_eggs(表示任一时刻可用的鸡蛋总数)、一个共享的 mutex(每当线程访问 num_eggs 时使用)和一个共享的条件变量 eggs。然后它创建两个母鸡线程和两个农夫线程:
The
mainfunction creates a shared variablenum_eggs(which indicates the total number of eggs available at any given time), a sharedmutex(which is used whenever a thread accessesnum_eggs), and a shared condition variableeggs. It then creates two Chicken and two Farmer threads:
1 | int main(int argc, char **argv){ |
每个母鸡线程负责下一定数量的蛋:
Each Chicken thread is responsible for laying a certain number of eggs:
1 | void *chicken(void *args ) { |
为了下一个蛋,母鸡线程先睡一会儿,然后获得互斥锁,把可用鸡蛋的总数加一。在释放互斥锁之前,母鸡线程「唤醒」一个正在睡觉的农夫(大概是靠咯咯叫)。母鸡线程重复这个循环,直到下完了它打算下的所有蛋(total_eggs)。
To lay an egg, a Chicken thread sleeps for a while, acquires the mutex and updates the total number of available eggs by one. Prior to releasing the mutex, the Chicken thread “wakes up” a sleeping Farmer (presumably by squawking). The Chicken thread repeats the cycle until it has laid all the eggs it intends to (
total_eggs).
每个农夫线程负责从这群母鸡那里收集 total_eggs 个鸡蛋(大概是当早饭):
Each Farmer thread is responsible for collecting
total_eggseggs from the set of chickens (presumably for their breakfast):
1 | void *farmer(void *args ) { |
每个农夫线程在检查共享变量 num_eggs、看是否有可用的鸡蛋(*num_eggs == 0)之前,都要先获得互斥锁。当没有可用的鸡蛋时,农夫线程就阻塞(即打个盹)。
Each Farmer thread acquires the mutex prior to checking the shared
num_eggsvariable to see whether any eggs are available (*num_eggs == 0). While there aren’t any eggs available, the Farmer thread blocks (i.e., takes a nap).
农夫线程因母鸡线程发出的信号而「醒来」后,会检查是否仍有鸡蛋可用(可能另一个农夫先拿走了),如果有,农夫就「收集」一个鸡蛋(把 num_eggs 减一)并释放互斥锁。
After the Farmer thread “wakes up” due to a signal from a Chicken thread, it checks to see that an egg is still available (another Farmer could have grabbed it first) and if so, the Farmer “collects” an egg (decrementing
num_eggsby one) and releases the mutex.
就这样,母鸡和农夫协同工作,下蛋/收蛋。条件变量确保在母鸡线程下蛋之前,没有哪个农夫线程会去收蛋。
In this manner, the Chicken and Farmer work in concert to lay/collect eggs. Condition variables ensure that no Farmer thread collects an egg until it is laid by a Chicken thread.
广播
Broadcasting
与条件变量一起使用的另一个函数是 pthread_cond_broadcast,当多个线程阻塞在某个特定条件上时,它很有用。调用 pthread_cond_broadcast(&cond) 会唤醒阻塞在条件 cond 上的所有线程。在下一个例子中,我们展示如何用条件变量实现前面讨论过的屏障结构:
Another function used with condition variables is
pthread_cond_broadcast, which is useful when multiple threads are blocked on a particular condition. Callingpthread_cond_broadcast(&cond)wakes up all threads that are blocked on conditioncond. In this next example, we show how condition variables can implement the barrier construct discussed previously:
1 | // mutex (initialized in main) |
函数 threadEx_v2 的功能与 threadEx 完全相同。在这个例子中,条件变量名为 barrier。每个线程获得锁之后,把 n_reached(已到达该点的线程数)加一。当到达屏障的线程数少于线程总数时,线程就在条件变量 barrier 和互斥锁 mutex 上等待。
The function
threadEx_v2has identical functionality tothreadEx. In this example, the condition variable is namedbarrier. As each thread acquires the lock, it incrementsn_reached, the number of threads that have reached that point. While the number of threads that have reached the barrier is less than the total number of threads, the thread waits on the condition variablebarrierand mutexmutex.
然而,当最后一个线程到达屏障时,它调用 pthread_cond_broadcast(&barrier),释放等待在条件变量 barrier 上的所有其他线程,使它们能够继续执行。
However, when the last thread reaches the barrier, it calls
pthread_cond_broadcast(&barrier), which releases all the other threads that are waiting on the condition variablebarrier, enabling them to continue execution.
这个例子很适合用来说明 pthread_cond_broadcast 函数;不过,只要程序中需要屏障,最好还是使用 Pthreads 的屏障原语。
This example is useful for illustrating the
pthread_cond_broadcastfunction; however, it is best to use the Pthreads barrier primitive whenever barriers are necessary in a program.
学生们常问的一个问题是:farmer 和 threadEx_v2 代码中围绕 pthread_cond_wait 调用的 while 循环,能否换成 if 语句?实际上,这个 while 循环是绝对必要的,主要有两个原因。第一,在被唤醒的线程回来继续执行之前,条件可能已经改变了。while 循环强制最后再检测一次条件。第二,pthread_cond_wait 函数可能出现虚假唤醒(spurious wakeup),即线程在条件可能并未满足的情况下被错误地唤醒。这个 while 循环实际上是谓词循环(predicate loop)的一个例子,它强制在释放互斥锁之前对条件做最后一次检查。因此,使用条件变量时,使用谓词循环是正确的做法。
One question that students tend to ask is if the
whileloop around the call topthread_cond_waitin thefarmerandthreadEx_v2code can be replaced with anifstatement. Thiswhileloop is in fact absolutely necessary for two main reasons. First, the condition may change prior to the woken thread arriving to continue execution. Thewhileloop enforces that the condition be retested one last time. Second, thepthread_cond_waitfunction is vulnerable to spurious wakeups, in which a thread is erroneously woken up even though the condition may not be met. Thewhileloop is in fact an example of a predicate loop, which forces a final check of the condition variable before releasing the mutex. The use of predicate loops is therefore correct practice when using condition variables.