[英]How do I protect a character string in shared memory between two processes?
I have a piece of shared memory that contains a char string and an integer between two processes.我有一块共享的 memory 包含一个字符字符串和一个 integer 在两个进程之间。
Process A writes to it and Process B reads it (and not vice versa)进程 A 写入它,进程 B 读取它(反之亦然)
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?确保进程 A 在进程 B 读取它的同时不会发生更新(写入)的最有效和最有效的方法是什么? (Should I just use flags in the shared memory, use semaphores, critical section....) (我是否应该只在共享 memory 中使用标志,使用信号量,临界区......)
If you could point me in the right direction, I would appreciate it.如果你能指出我正确的方向,我将不胜感激。
Thanks.谢谢。
Windows, C++ Windows, C++
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 .对于进程间同步,您需要使用Mutex或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.在您的情况下,互斥锁似乎合适。
A mutex object facilitates protection against data races and allows thread-safe synchronization of data between threads.互斥锁 object 有助于防止数据竞争,并允许线程之间的数据线程安全同步。 A thread obtains ownership of a mutex object by calling one of the lock functions and relinquishes ownership by calling the corresponding unlock function.线程通过调用其中一个锁定函数获得互斥体 object 的所有权,并通过调用相应的解锁 function 放弃所有权。
If you are using boost thread, you can use it's mutex and locking, more to read see the link below:如果您使用的是 boost 线程,则可以使用它的互斥锁和锁定,更多内容请参见下面的链接:
http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types
Since you're talking about two processes, system-wide mutexes will work, and Windows has those.由于您在谈论两个进程,因此系统范围的互斥锁将起作用,并且 Windows 拥有这些。 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.如果您可以在共享 memory 中放入更多内容,那么通过 memory 中的标志的原子操作传递数据应该是最有效的做法。 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).例如,您可以使用Interlocked 函数来实现Dekker 算法(您可能希望使用YieldProcessor()
类的东西来避免忙于等待)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.