Linux 如何在C中初始化二进制信号量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7478684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:16:57  来源:igfitidea点击:

How to initialise a binary semaphore in C

clinuxsemaphoreinit

提问by austinmarton

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

手册页中,即使您将信号量初始化为值 1:

sem_init(&mySem, 0, 1);

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

它仍然可以通过多次调用增加到大于 1 的值

sem_post(&mySem);

But in this code examplethe comment seems to think differently:

但在这个代码示例中,注释似乎有不同的想法:

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

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

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

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.

注意:在这种情况下这样做而不是使用互斥锁的原因是 sem_post 和 sem_wait 可能被不同的线程调用。

采纳答案by Dietrich Epp

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

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

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);
}