Atomic unlocked access to 64bit blocks of Memory Mapped Files in .NET

我是研究僧i 提交于 2020-01-06 03:52:09

问题


We need to share very efficiently block of constantly changing information between two processes. Information fits in 64bits block of memory - so inside one process we'd be able to use Interlocked operations (or probably even just ordinary reads/writes) to ensure lock-free access to correct state of information (not just partially written).

How can we write and ready block of 64bit data into MMF without locking and synchronization in order to make sure that we don't read partially written data? Aren't writes of this size atomic by itself on 64bit architecture? But aligning could probably make it non-atomic, correct?

So is using Interlocked operations (e.g. via the way described in this question: How to use interlocked operations against memory-mapped files in .Net) on MMF the way to go? But couldn't we have the problems with aligning even in this case (as MMF is block of memory and so .NET might not control it's aligning as it does with variables)?


回答1:


How can we write and ready block of 64bit data into MMF without locking and synchronization in order to make sure that we don't read partially written data? Aren't writes of this size atomic by itself on 64bit architecture? But aligning could probably make it non-atomic, correct?

Memory mapped files are page aligned under the covers, so keep your data aligned in your MMF. Then, if you write a 64-bit integer on a 64-bit processor with a 64-bit instruction to a 64-bit aligned location, there should be no chance of another processor reading a partially written value at that location.

[Edit] See the article Managing Memory-Mapped File (MSDN) which describes one implementation of MMF files as system page files. Also see this Wiki as general info on MMF which states MMFs are always page aligned.

So is using Interlocked operations (e.g. via the way described in 'cited' question: How to use interlocked operations against memory-mapped files in .Net) on MMF the way to go? But couldn't we have the problems with aligning even in this case (as MMF is block of memory and so .NET might not control it's aligning as it does with variables)?

There shouldn't be any alignment issues with the example you've cited.



来源:https://stackoverflow.com/questions/23835932/atomic-unlocked-access-to-64bit-blocks-of-memory-mapped-files-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!