C semaphore与 Mutex Condition Variables
Semaphore(信号量)
C中有两个信号量的头文件<semaphore.h>
和<sys/sem.h>。
<sys/sem.h>
provides the interface for XSI (originally Unix System V) semaphores.
<semaphore.h>
defines POSIX semaphores.
所以这里只写关于<semaphore.h>的。
/* * ==================== * ==================== * Semaphores, Mutexes and Condition Variables * ==================== * ==================== */ struct sem_t_ { int value; pthread_mutex_t lock; HANDLE sem; #if defined(NEED_SEM) int leftToUnblock; #endif };
int sem_init (sem_t * sem,int pshared,unsigned int value); int sem_destroy (sem_t * sem); int sem_trywait (sem_t * sem); int sem_wait (sem_t * sem); int sem_timedwait (sem_t * sem,const struct timespec * abstime); int sem_post (sem_t * sem); int sem_post_multiple (sem_t * sem,int count); int sem_getvalue (sem_t * sem,int * sval); //没有实现的有 int sem_open (const char * name,int oflag,mode_t mode,unsigned int value); int sem_close (sem_t * sem); int sem_unlink (const char * name);
semaphore与 Mutex Condition Variables 在一些情况下是等价的,但一个区别在于,Mutex Condition Variables可以实现原子操作,
如果semaphore一次signal 2个信号,那么可能有两个线程出现竞争。