使用互斥锁mutex实现信号量sem

25 篇文章 1 订阅

/* ======================== 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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值