c - 使用信号量通过 for 循环实现进程之间的同步

标签 c multithreading semaphore

上下文:

  • 我试图让两个进程写入共享内存空间中的同一个数组。

  • 每个进程都会用 for 循环写入数组的一半。

  • 数组的第一个元素将始终存储下一个要写入的元素的索引。

  • IPC是通过共享内存中的信号量完成的。

先决条件:

  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

最佳答案

看看你的实际代码,我认为问题在于你如何创建信号量。如果您阅读 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.

这里的关键是以粗体显示的文本 - 您的信号量不在共享内存中,因此它并未在两个进程之间真正共享,因此您会看到争用。

关于c - 使用信号量通过 for 循环实现进程之间的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39742229/

相关文章:

c - C语言中如何比较字符串?这个错误 "warning: comparison between pointer and integer"是什么意思?

c++ - c中的类型提升和转换

mysql LAST_INSERT_ID 带参数序列实现

java - 引用分配是原子的,所以为什么要使用 AtomicReference

java线程池任务超时问题

Java 信号量不遵守提供的参数?

c++ - 从 USB 读取 rfid 标签

Java——线程执行顺序

主线程上的 IOS semaphore_wait_trap 导致 UI 挂起

将 Int 转换为 char* 指针