“In computer science, a semaphore is a variable or abstract data type that provides a simple but useful abstraction for controlling access by multiple processes to a common resource in a parallel programming environment.
A useful way to think of a semaphore is as a record of how many units of a particular resource are available, coupled with operations to safely (i.e., without race conditions) adjust that record as units are required or become free, and if necessary wait until a unit of the resource becomes available. Semaphores are a useful tool in the prevention of race conditions and deadlocks; however, their use is by no means a guarantee that a program is free from these problems. Semaphores which allow an arbitrary resource count are called counting semaphores, while semaphores which are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores (same functionality that mutexes have).”。
其中关键信息主要是“a semaphore is a data type for controlling access by multiple processes to a common resource in a parallel programming environment... Semaphores which allow an arbitrary resource count are called counting semaphores, while semaphores which are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores (same functionality that mutexes have)”,也即信号量在并行处理环境下对多个processes访问某个公共资源进行保护,后面提到的binary semaphore,本质上应该就是mutex了,从same functionality that mutexes have这句话来看,mutex和binary semaphore功能应该相同。从以上的文字中显然可以看到,相对mutex而言信号量的适用范围更广(mutex只是信号量的用途之一),这个我们接 下来在后续的Linux源码中也可以看到这其中某些细微之处的区分。
*注:昨天写这个帖子时手头没有操作系统方面的书籍拿来参考,今天我翻了一下《现代操作系统》(陈向群等译,机械工业出版社 1999年11月第1 版), 关于这个话题,书里明确提到的只有"2.2.5 信号量",至于mutex,书中并没有作为一个独立的概念提出来,只是在讲信号量时提到了上面所说的binary semaphore,并且说“信号量mutex(应该是指binary semaphore)用于互斥...互斥是避免混乱所必需的操作...信号量的另一种用途是用于实现同步(synchronization)。信号量 full和empty用来保证一定的事件顺序发生或不发生。在本例中,它们保证缓冲区满的时候生产者停止运行,或者当缓冲区空的时候消费者停止运行。这种 用法与互斥是不同的” --- P30-31 *
OK,理论上的概念有了,那么就来看看实际当中Linux下的semaphone到底长的啥样。以下是semaphore在Linux源码中的定义,源码来自3.2.9:
- /* Please don't access any members of this structure directly */
- struct semaphore {
- raw_spinlock_t lock;
- unsigned int count;
- struct list_head wait_list;
- };
- #define DECLARE_MUTEX(name) \
- struct semaphore name = __SEMAPHORE_INITIALIZER(name, 1)
那么既然count=1的信号量可以用来完成mutex lock的功能,那么内核何必再多此一举弄出个mutex lock出来呢?