共享内存 - 需要同步 [英] Shared memory - need for synchronization

查看:421
本文介绍了共享内存 - 需要同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一个项目,其中进程之间的通信使用共享内存(例如在Windows下使用 :: CreateFileMapping ),每当有一个进程想通知一些数据在共享内存中可用,使用命名事件的同步机制通知感兴趣方共享内存的内容发生了变化。

I've seen a project where communication between processes was made using shared memory (e.g. using ::CreateFileMapping under Windows) and every time one of the processes wanted to notify that some data is available in shared memory, a synchronization mechanism using named events notified the interested party that the content of the shared memory changed.

我关注的事实对于读取新信息的进程,不存在适当的存储器栅栏,以知道它必须使其数据的副本无效,并且一旦其被制造者进程发布,就从主存储器读取它。

I am concerned on the fact that the appropriate memory fences are not present for the process that reads the new information to know that it has to invalidate it's copy of the data and read it from main memory once it is "published" by the producer process.

你知道如何在Windows上使用共享内存实现这一点吗?

Do you know how can this be accomplished on Windows using shared memory?

EDIT
只是希望补充说,在创建文件映射之后,进程只使用一次MapViewOfFile()API,每次对共享数据的新修改都使用通过初始调用MapViewOfFile()获得的指针来读取通过共享内存发送的新数据。正确的同步要求每次数据在共享内存中改变时,读取数据的过程必须每次都创建MapViewOfFile()。

EDIT Just wanted to add that after creating the file mapping the processes uses MapViewOfFile() API only once and every new modification to the shared data uses the pointer obtained by the initial call to MapViewOfFile() to read the new data sent over the shared memory. Does correct synchronization require that every time data changes in shared memory the process that reads data must create MapViewOfFile() every time ?

推荐答案

进程A更改​​数据并调用 SetEvent

Process A changes the data and calls SetEvent.

进程B使用 WaitForSingleObject 或类似的方法等待事件,

Process B waits for the event using WaitForSingleObject or similar, and sees that it is set.

然后,进程B读取数据。 WaitForSingleObject 包含所有必要的同步,以确保在调用 SetEvent 之前由进程A进行的更改被进程读取B.

Process B then reads the data. WaitForSingleObject contains all the necessary synchronization to ensure that the changes made by process A before the call to SetEvent are read by process B.

当然,如果您在 之后对数据进行任何更改 SetEvent

Of course, if you make any changes to the data after calling SetEvent, then these may or may not show up when process B reads the data.

如果您不想使用事件,您可以使用创建的 CreateMutex ,或者可以使用 Interlocked ... 函数写入无锁代码,例如 InterlockedExchange InterlockedIncrement

If you don't want to use Events, you could use a Mutex created with CreateMutex, or you could write lock-free code using the Interlocked... functions such as InterlockedExchange and InterlockedIncrement.

但是您进行同步,请多次调用 MapViewOfFile

However you do the synchronization, you do not need to call MapViewOfFile more than once.

这篇关于共享内存 - 需要同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆