How to use memmapfiles safely for inter-process communication?
9 views (last 30 days)
Show older comments
I am interested in using memory mapped files to implement inter-process communication between a Matlab process and a foreign process. Portability (Windows / Linux) is a concern, but my main concern is reliability.
Looking at the example in Share Memory Between Applications, I am surprised the code is that simple. Does the code actually work? The shared byte m.Data(1) controls which process is allowed to access the shared data, but m.Data(1) itself doesn't seem to be protected against data races. To implement this example in C++, one would typically add some synchronization object, either a locking one (mutex, semaphore or condition variable) or a lock-free one (involving some kind of memory barrier). The Boost library provides some good examples of such mechanisms.
Can we use such synchronization objects with Matlab's memmapfiles? Or is there some kind of magic the Matlab compiler adds behind the scenes, that makes my concern pointless?
Edit: I am specifically concerned by the compiled code of this example.
0 Comments
Answers (1)
Philip Borghesani
on 8 Jun 2017
In MATLAB on Intel (x86) platforms I believe this code is safe and will work correctly. Because the communication process is token based and designed to only work between two processes a simple mechanism is possible. If this was done in C with a memory mapped file the only change needed would be to declare the first memory location atomic.
Also note that this is not the most efficient way to do this type of thing. The sleep calls dictate the maximum call throughput and the poling mechanism is inefficient. Doing this with one or two mex files and proper inter-process communication would have much better performance.
11 Comments
Walter Roberson
on 14 Jun 2017
If you were to access m.data(I,J) with vector I or J then the order of the accesses to the elements is not defined and could be different for large enough arrays (because the pattern of copying out to call the high performance libraries could be different)
See Also
Categories
Find more on Detection in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!