如何等到其他过程初始化共享内存?

发布于 2025-02-13 12:36:49 字数 523 浏览 0 评论 0原文

我有两个过程A和B,它们正在使用共享内存。我希望Process B等待使用共享内存,直到由进程A完全初始化。

// process A
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
(create and initialize shared memory here)
sem_post(s);
// process B
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
sem_wait(s);
(load and use shared memory here)

但是,如果我首先开始处理A,则过程B将陷入SEM_WAIT。这对我来说没有意义,因为我假设过程A中的sem_post(s)也会在过程B中递增柜台中的计数器,因为它似乎在某种程度上是“共享”的。

修改此代码以确保过程B等待过程A初始化共享内存的最简单方法是什么,而无需假设过程B将首先启动?

I have two processes, A and B, that are using shared memory. I want process B to wait to use the shared memory until it is completely initialized by process A. To coordinate this, I am attempting to use a named semaphore.

// process A
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
(create and initialize shared memory here)
sem_post(s);
// process B
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
sem_wait(s);
(load and use shared memory here)

However, if I start process A first, process B will get stuck at sem_wait. This does not make sense to me, because I would assume that the sem_post(s) in process A will increment the counter in the named semaphore for process B, too, since it seems to be "shared" in a way.

What is the easiest way to modify this code to make sure that process B will wait for process A to initialize the shared memory, without assuming that process B will start first?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

极致的悲 2025-02-20 12:36:49

对于某些操作系统,有特定的障碍机制,这将是优势。

通常,还可以选择使用MUTEX/独家区域来保护标志(变量)来指示初始化状态。因此,您只是睡觉并阅读值,而不是等待操作系统再次激活任务。通过这种方法,过程顺序不会影响结果。

For some OS, there is specific mechanism for barrier and it would be advantage.

In general, there is also option to use mutex/exclusive area to protect a flag (variable) to indicate the initialization status. So instead of waiting OS to activate your task again, you just sleep and read the value. With this approach, the process order will not impact to the result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文