如何保护两个进程之间共享内存中的字符串?
我有一块共享内存,其中包含两个进程之间的一个字符串和一个整数。
进程 A 写入它,进程 B 读取它(反之亦然)
什么是最有效和有效的方法来确保进程 A 不会在进程 B 读取它的同时更新(写入它)? (我应该在共享内存中使用标志,使用信号量,临界区......)
如果你能指出我正确的方向,我将不胜感激。
谢谢。
视窗、C++
I have a piece of shared memory that contains a char string and an integer between two processes.
Process A writes to it and Process B reads it (and not vice versa)
What is the most efficient and effective way to make sure that Process A doesn't happen to update (write to it) that same time Process B is reading it? (Should I just use flags in the shared memory, use semaphores, critical section....)
If you could point me in the right direction, I would appreciate it.
Thanks.
Windows, C++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能使用关键部分,因为它们可以只用于同一进程内线程之间的同步。对于进程间同步,您需要使用 互斥体< /a> 或 信号量。两者之间的区别在于,前者仅允许单个线程拥有资源,而后者可以允许最多数量(在创建期间指定)同时拥有资源。
在你的情况下,互斥体似乎是合适的。
You cannot use a Critical Section because these can only be used for synchronization between threads within the same process. For inter process synchronization you need to use a Mutex or a Semaphore. The difference between these two is that the former allows only a single thread to own a resource, while the latter can allow up to a maximum number (specified during creation) to own the resource simultaneously.
In your case a Mutex seems appropriate.
由于您有两个进程,因此需要一个跨进程同步对象。我认为这意味着您需要使用 互斥体。
Since you have two processes you need a cross-process synchronisation object. I think this means that you need to use a mutex.
如果您使用boost线程,您可以使用它的互斥锁和锁定,更多内容请参阅下面的链接:
http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types
If you are using boost thread, you can use it's mutex and locking, more to read see the link below:
http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types
由于您谈论的是两个进程,因此系统范围的互斥体将起作用,并且 Windows 具有这些互斥体。然而,它们不一定是最有效的方法。
如果您可以将更多内容放入共享内存中,那么通过对该内存中的标志进行原子操作来传递数据应该是最有效的做法。例如,您可以使用互锁函数 实施 Dekker 的算法(您可能需要使用类似
YieldProcessor()
以避免忙等待)。Since you're talking about two processes, system-wide mutexes will work, and Windows has those. However, they aren't necessarily the most efficient way.
If you can put more things in shared memory, then passing data via atomic operations on flags in that memory should be the most efficient thing to do. For instance, you might use the Interlocked functions to implement Dekker's Algorithm (you'll probably want to use something like
YieldProcessor()
to avoid busy waiting).