gpt4 book ai didi

c - 信号量 System V - semop 实现

转载 作者:行者123 更新时间:2023-11-30 15:01:26 26 4
gpt4 key购买 nike

正如您在信号量 System V 文档 ( http://man7.org/linux/man-pages/man2/semop.2.html ) 中看到的,有一部分声明了以下内容:

EXAMPLE

The following code segment uses semop() to atomically wait for the value of semaphore 0 to become zero, and then increment the semaphore value by one.

      struct sembuf sops[2];
int semid;

/* Code to set semid omitted */

sops[0].sem_num = 0; /* Operate on semaphore 0 */
sops[0].sem_op = 0; /* Wait for value to equal 0 */
sops[0].sem_flg = 0;

sops[1].sem_num = 0; /* Operate on semaphore 0 */
sops[1].sem_op = 1; /* Increment value by one */
sops[1].sem_flg = 0;

if (semop(semid, sops, 2) == -1) {
perror("semop");
exit(EXIT_FAILURE);
}

在这个例子之后我有几个问题:

1- (semop(semid, sops, 2) == -1) 是否执行 2 个 sops 位置? sops[0] 和 sops[1]?

2- 如果是这样,为什么 sops[0].sem_op = 0; 等待 semid 的值等于 0?

最佳答案

1- Does (semop(semid, sops, 2) == -1) executes the 2 sops positions? sops[0] and sops[1]?

它试图这样做,是的。这就是 semop() 函数所做的,它必须运行才能返回一个值(然后示例代码会针对 -1 进行测试)。与许多 C 函数一样,semop() 失败时返回 -1;在这种情况下,对于该函数,您可以依赖未执行的任何操作。否则,semop() 返回 0,在这种情况下,您可以依赖已执行的两个操作。

2- If so why does sops[0].sem_op = 0; Waits for value of the semid to equal 0?

因为这就是 sem_op 值的定义含义。正如您自己链接的文档所说:

If sem_op is zero, the process must have read permission on the semaphore set. This is a "wait-for-zero" operation [...]

关于c - 信号量 System V - semop 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41399511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com