Linux semaphore 阅读笔记


include/linux/semaphore.h
kernel/semaphore.c

struct semaphore {
     spinlock_t lock;
     unsigned int count;
     struct list_head wait_list;
};

信号量本质上是一个计数器。count不为0时进程可以获得信号量,count为0时进程无法获得信号量,因而可能进入休眠。
当count初始为1时,其作用类似于互斥量mutex。但linux中的mutex实现机制已经不再使用semaphore,而使用另一套更简单有效的方法。
信号量用于资源可以同时被多个进程使用时的场景。

void sema_init(struct semaphore *sem, int val);
用val初始信号量的count。

void down(struct semaphore *sem);
获得信号量。如果无法获得则进程进入休眠,直到该信号量在其他地方被释放。不推荐使用此函数,因为其在休眠时将进程状态置为TASK_UNINTERRUPTIBLE.

int down_interruptible(struct semaphore *sem);
同down()函数,但休眠时将进程状态置为TASK_INTERRUPTIBLE。此时进程虽然休眠,但可以被信号中断。此时down_interruptible()函数返回-EINTR。

int down_killable(struct semaphore *sem);
同down()函数,但休眠时进程状态为TASK_KILLABLE,即进程休眠时仍可被某些信号杀死。

int down_trylock(struct semaphore *sem);
同down(),但无法获得信号量时立即返回1,而不是使进程休眠。

int down_timeout(struct semaphore *sem, long jiffies);
同down(),但在jiffies时间超时后还无法获得信号时,则函数返回-ETIME.

void up(struct semaphore *sem);
释放信号量。


semaphore的wait_list成员用于记录正在等待此信号量的进程。
__down_common()函数做了进程休眠工作:设置进程状态state,然后使用schedule_timeout()将CPU换出。

posted @ 2013-02-25 16:36  sammei  阅读(1750)  评论(0编辑  收藏  举报