使用互斥鎖mutex實現訊號量sem
/* ======================== SYNCHRONISATION ========================= */
/* Init semaphore to 1 or 0 */
void bsem_init(bsem *bsem_p, int value) {
if (value < 0 || value > 1) {
err(“bsem_init(): Binary semaphore can take only values 1 or 0”);
exit(1);
}
pthread_mutex_init(&(bsem_p->mutex), NULL);
pthread_cond_init(&(bsem_p->cond), NULL);
bsem_p->v = value;
}
/* Reset semaphore to 0 */
void bsem_reset(bsem *bsem_p) {
bsem_init(bsem_p, 0);
}
/* Post to at least one thread */
void bsem_post(bsem *bsem_p) {
pthread_mutex_lock(&bsem_p->mutex);
bsem_p->v = 1;
pthread_cond_signal(&bsem_p->cond);
pthread_mutex_unlock(&bsem_p->mutex);
}
/* Post to all threads */
void bsem_post_all(bsem *bsem_p) {
pthread_mutex_lock(&bsem_p->mutex);
bsem_p->v = 1;
pthread_cond_broadcast(&bsem_p->cond);
pthread_mutex_unlock(&bsem_p->mutex);
}
/* Wait on semaphore until semaphore has value 0 */
void bsem_wait(bsem* bsem_p) {
pthread_mutex_lock(&bsem_p->mutex);
while (bsem_p->v != 1) {
pthread_cond_wait(&bsem_p->cond, &bsem_p->mutex);
}
bsem_p->v = 0;
pthread_mutex_unlock(&bsem_p->mutex);
}
/* Wait on semaphore until semaphore has value 0
* return:
* ETIMEDOUT: not waited mutex ,time out
* 0: waited mutex, and return 0;
*/
int bsem_timewait(bsem* bsem_p, int second) {
int ret;
struct timeval _now;
struct timespec outtime;
pthread_mutex_lock(&bsem_p->mutex);
while (bsem_p->v != 1) {
gettimeofday(&_now, NULL);
outtime.tv_sec = _now.tv_sec + second;
outtime.tv_nsec = _now.tv_usec * 1000;
ret = pthread_cond_timedwait(&bsem_p->cond, &bsem_p->mutex, &outtime);
if(ret == ETIMEDOUT){
break;
}
}
bsem_p->v = 0;
pthread_mutex_unlock(&bsem_p->mutex);
return ret;
}