使用信号量的 for 循环在进程之间同步

Synchronization between processes with for loops using semaphores

上下文:

先决条件:

  1. 数组和信号量都已在共享内存中正确设置。
  2. 如果我在 for 循环之外等待 sem_wait 和 sem_post,程序工作正常,这意味着使整个过程原子化。 (这也是我认为信号量和数组设置正确的原因)

问题

然而,当我试图通过将 sem_wait 和 sem_post 放入 for 循环来减少临界区时。它不是同步的,因为数组的一部分没有被写入。但是这两个进程完成了它们的循环,总循环计数应该等于数组长度。

非常感谢建议为什么会这样???


更新

在 OS X 上,sem_init() 未按预期工作。使用 sem_open() 来解决问题。 参考:http://lists.apple.com/archives/darwin-dev//2008/Oct/msg00044.html

在问题案例的伪代码中,父线程一释放就需要信号量。现在,由于信号量可用,parent 将继续执行。当它的时间片到期时,内核可能会切换到子进程,但它正在等待信号量。信号量由父进程获取。所以父级将再次继续执行。

在这个场景中,parent执行了两次,child没有执行。

这可能导致执行不同步。

查看您的实际代码,我认为问题在于您如何创建信号量。如果您阅读 sem_init 上的手册页:

If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)). (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.) Any process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), and so on.

此处的关键是粗体文本 - 您的信号量不在共享内存中,因此它并没有真正在两个进程之间共享,因此您看到了争用。