所以我遇到了一个问题,我真的不知道该怎么办。我希望你能告诉我如何处理它。
我需要在共享内存中分配 N 个缓冲区。每个缓冲区都应初始化为 0。然后我必须 fork N/2 个子进程。
然后每个 child (i)将值(i)写入缓冲区(i),休眠一秒钟。然后读取当前缓冲区的值,如果值在此期间发生变化,则显示一条消息。然后 child 移动 i 个位置 N/2 次。
So I can have
N Buffers = 11. (must be prime)
N/2 children = 5.
So child 2 would:
write into buffer 2, sleep, read from buffer 2. (now move 2 positions)
write into buffer 4, sleep, read from buffer 4. (now move 2 positions)
**remmeber we only have five buffers so we go around again*****
write into buffer 1, sleep, read from buffer 1. (now move 2 positions)
write into buffer 3, sleep, read from buffer 3. (now move 2 positions)
write into buffer 5, sleep, read from buffer 5. ***we stop moving here. N/2 moves already performed.
知道应该怎么做吗?
- 我可以只创建一个包含 N 个整数的数组吗?由于所有 child 都将访问相同的元素,这会成为问题吗?
最佳答案
关于在 C 中创建访问共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1664519/