在信号量(操作系统)中传递给 sem_init() 的参数的含义是什么?

What are the meanings of parameters passed to sem_init() in Semaphores(Operating Systems)?

考虑下面给出的代码片段:

    #include <pthread.h>
    #include <semaphore.h>

    sem_t empty;
    sem_t full;
    sem_t mutex;

    int main(int argc, char *argv[]) 
    {
    int MAX = 10;//Size of the Buffer
    sem_init(&empty, 0, MAX);
    sem_init(&full, 0, 0);
    sem_init(&mutex, 0, 1);

    return 0;
    }

只有需要的代码,我上面已经提到了。它是生产者-消费者代码的一部分。 sem_init()中各个参数的含义是什么?我可以看出第一个参数是信号量变量的地址,第三个参数是它的值。

为什么第二个参数总是0?这是什么意思?

我们是否使用第二个参数指定等待信号量的临界值?

    wait(S) {
    while (S <= 0 )
    ; // busy wait
    S--;
    }

如果我将 3 作为第二个参数传递给 sem_init(),wait(S) 中的 while 循环是否会更改为

while (S <= 3 )

像这样?

请看http://man7.org/linux/man-pages/man3/sem_init.3.html。关于第二个参数:

The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes.

这本质上是布尔值,但请阅读 link 了解更多信息。如果你真的是线程,那么这应该总是 0,在极端情况下,你在不同进程上使用线程代码使用非零。

始终尝试阅读 Linux 文档 (man <command or system_call>) 以解决此类疑虑。

你的情况man sem_init
sem_init() 在指向的地址处初始化未命名信号量 到 sem。 value 参数指定的初始值 信号。

web link 手册页