说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C14-SharedMemory/semaphores.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
14.3.2. Semaphores
信号量(semaphore)常用于操作系统和并发程序中,目的是管理对一个资源池的并发访问。使用信号量时,关注的不是谁拥有什么,而是还有多少资源可用。信号量与互斥锁在几个方面有所不同:
Semaphores are commonly used in operating systems and concurrent programs where the goal is to manage concurrent access to a pool of resources. When using a semaphore, the goal isn’t who owns what, but how many resources are still available. Semaphores are different from mutexes in several ways:
- 信号量不一定只有二元(加锁或未加锁)的状态。一种称为计数信号量(counting semaphore)的特殊信号量,其值的范围可以从 0 到某个 r,其中 r 是可能的资源数。每当生产出一个资源,信号量就加一。每当一个资源被使用,信号量就减一。当计数信号量的值为 0 时,表示没有可用的资源,任何其他试图获取资源的线程都必须等待(即阻塞)。
- Semaphores need not be in a binary (locked or unlocked) state. A special type of semaphore called a counting semaphore can range in value from 0 to some r, where r is the number of possible resources. Any time a resource is produced, the semaphore is incremented. Any time a resource is being used, the semaphore is decremented. When a counting semaphore has a value of 0, it means that no resources are available, and any other threads that attempt to acquire a resource must wait (e.g., block).
- 信号量可以默认处于加锁状态。
- Semaphores can be locked by default.
尽管互斥锁和条件变量可以模拟信号量的功能,但在某些情况下,使用信号量可能更简单、更高效。信号量还有一个优点:任何线程都可以给信号量解锁(与之相对,互斥锁必须由加锁的线程来解锁)。
While a mutex and condition variables can simulate the functionality of a semaphore, using a semaphore may be simpler and more efficient in some cases. Semaphores also have the advantage that any thread can unlock the semaphore (in contrast to a mutex, where the calling thread must unlock it).
信号量不属于 Pthreads 库,但这并不意味着你不能使用它们。在 Linux 和 macOS 系统上,可以通过 semaphore.h 使用信号量原语,这个头文件通常位于 /usr/include 中。由于没有统一的标准,不同系统上的函数调用可能有所不同。尽管如此,信号量库的声明与互斥锁的类似:
Semaphores are not part of the Pthreads library, but that does not mean that you cannot use them. On Linux and macOS systems, semaphore primitives can be accessed from
semaphore.h, typically located in/usr/include. Since there is no standard, the function calls may differ on different systems. That said, the semaphore library has similar declarations to those of mutexes:
译注
说「没有标准」并不准确:按 sem_init(3) 手册,sem_init 等函数属于 POSIX 标准(POSIX.1-2001 起,现为 POSIX.1-2008),在 Linux 上由 POSIX 线程库提供。各系统的差异主要在于实现的完整程度,见下面关于 macOS 的译注。
- 声明一个信号量(类型为
sem_t,例如sem_t semaphore)。
- Declare a semaphore (type
sem_t, e.g.,sem_t semaphore).
- 用
sem_init初始化信号量(通常在main中)。sem_init函数有三个参数:第一个是信号量的地址,第二个是它的初始状态(加锁或未加锁),第三个参数表示信号量是在一个进程的各线程之间共享(例如取值 0),还是在进程之间共享(例如取值 1)。这很有用,因为信号量常用于进程同步。例如,用调用sem_init(&semaphore, 1, 0)初始化信号量,表示我们的信号量初始时是加锁的(第二个参数为 1),并且要在同一个进程的各线程之间共享(第三个参数为 0)。与之不同,互斥锁总是以未加锁状态开始。需要注意的是,在 macOS 中,等价的函数是sem_open。
- Initialize a semaphore using
sem_init(usually inmain). Thesem_initfunction has three parameters: the first is the address of a semaphore, the second is its initial state (locked or unlocked), and the third parameter indicates whether the semaphore should be shared with the threads of a process (e.g., with value 0) or between processes (e.g., with value 1). This is useful because semaphores are commonly used for process synchronization. For example, initializing a semaphore with the callsem_init(&semaphore, 1, 0)indicates that our semaphore is initially locked (the second parameter is 1), and is to be shared among the threads of a common process (the third parameter is 0). In contrast, mutexes always start out unlocked. It is important to note that in macOS, the equivalent function issem_open.
译注 · 参数顺序写反了
按 sem_init(3) 手册,原型是 int sem_init(sem_t *sem, int pshared, unsigned int value);:第二个参数 pshared 决定共享范围(0 表示在一个进程的各线程间共享,非 0 表示在进程间共享),第三个参数 value 是信号量的初始值(0 即「加锁」,没有可用资源)。所以 sem_init(&semaphore, 1, 0) 实际表示「初始值为 0、在进程间共享」;本章这类多线程用法应写成 sem_init(&semaphore, 0, 0)。
另外,在 macOS 上 sem_init 并不能用:译者在 Mac 上编译调用 sem_init(&s, 0, 1) 的程序,Clang 给出「’sem_init’ is deprecated」警告,运行时它返回 -1,errno 为「Function not implemented」。因此在 Mac 上要么改用有名信号量 sem_open,要么在 Linux 中运行本节的例子。
- 用
sem_destroy销毁信号量(通常在main中)。这个函数只接收一个指向信号量的指针(sem_destroy(&semaphore))。注意,在 macOS 中,等价的函数可能是sem_unlink或sem_close。
- Destroy a semaphore using
sem_destroy(usually inmain). This function only takes a pointer to the semaphore (sem_destroy(&semaphore)). Note that in macOS, the equivalent function may besem_unlinkorsem_close.
sem_wait函数表示一个资源正在被使用,并把信号量减一。如果信号量的值大于 0(表示仍有可用的资源),函数会立即返回,线程可以继续执行。如果信号量的值已经是 0,线程就会阻塞,直到有资源可用(即信号量的值为正)。对sem_wait的调用通常写作sem_wait(&semaphore)。
- The
sem_waitfunction indicates that a resource is being used, and decrements the semaphore. If the semaphore’s value is greater than 0 (indicating there are still resources available), the function will immediately return, and the thread is allowed to proceed. If the semaphore’s value is already 0, the thread will block until a resource becomes available (i.e., the semaphore has a positive value). A call tosem_waittypically looks likesem_wait(&semaphore).
sem_post函数表示一个资源正在被释放,并把信号量加一。这个函数会立即返回。如果有线程在等待这个信号量(即信号量之前的值为 0),那么那个线程将取得被释放资源的所有权。对sem_post的调用写作sem_post(&semaphore)。
- The
sem_postfunction indicates that a resource is being freed, and increments the semaphore. This function returns immediately. If there is a thread waiting on the semaphore (i.e., the semaphore’s value was previously 0), then the other thread will take ownership of the freed resource. A call tosem_postlooks likesem_post(&semaphore).