如何初始化在C二进制信号 [英] How to initialise a binary semaphore in C

查看:196
本文介绍了如何初始化在C二进制信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

手册页看来,即使你初始化一个信号一个值:

In the man page it appears that even if you initialise a semaphore to a value of one:

sem_init(&mySem, 0, 1);

有可能仍然被递增到具有多个呼叫的大于1的值,以

It could still be incremented to a value greater than 1 with multiple calls to

sem_post(&mySem);

但在这个 code例如的评论似乎有不同的看法:

But in this code example the comment seems to think differently:

sem_init(&mutex, 0, 1);      /* initialize mutex to 1 - binary semaphore */

是否可以初始化在C严格的二进制信号?

Is it possible to initialise a strictly binary semaphore in C?

*注意:这样做的原因,而不是在这种情况下使用互斥是sem_post和sem_wait可以由不同的线程调用*

*Note: The reason for doing this instead of using a mutex in this case is the sem_post and sem_wait may be called by different threads.*

推荐答案

如果你想在Linux上严格的二进制信号,我建议建立一出来互斥体和条件变量。

If you want a strictly binary semaphore on Linux, I suggest building one out of mutexes and condition variables.

struct binary_semaphore {
    pthread_mutex_t mutex;
    pthread_cond_t cvar;
    int v;
};

void mysem_post(struct binary_semaphore *p)
{
    pthread_mutex_lock(&p->mutex);
    if (p->v == 1)
        /* error */
    p->v += 1;
    pthread_cond_signal(&p->cvar);
    pthread_mutex_unlock(&p->mutex);
}

void mysem_wait(struct binar_semaphore *p)
{
    pthread_mutex_lock(&p->mutex);
    while (!p->v)
        pthread_cond_wait(&p->cvar, &p->mutex);
    p->v -= 1;
    pthread_mutex_unlock(&p->mutex);
}

这篇关于如何初始化在C二进制信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆