说明
在某些平台,信号量可能并不支持,可以使用互斥锁和条件变量模拟实现信号量,代码如下
代码
typedef struct {
int val; //信号量的值
pthread_mutex_t mutex;
pthread_cond_t cond;
} semaphore_t;
inline void sem_init(semaphore_t *s, int n)
{
pthread_mutex_init(&(s->mutex), NULL);
pthread_cond_init(&(s->cond), NULL);
s->val = n;
}
inline void sem_post(semaphore_t *s)
{
pthread_mutex_lock(&(s->mutex));
s->val++;
pthread_cond_signal(&(s->cond));
pthread_mutex_unlock(&(s->mutex));
}
inline int sem_wait(semaphore_t *s)
{
int rc = 0;
pthread_mutex_lock(&(s->mutex));
while (s->val == 0)
rc = pthread_cond_wait(&(s->cond), &(s->mutex));
s->val--;
pthread_mutex_unlock(&(s->mutex));
return rc;
}
inline void sem_destroy(semaphore_t *s)
{
pthread_mutex_destroy(&(s->mutex));
pthread_cond_destroy(&(s->cond));
s->val = 0;
}