Question

Two Windows processes have memory mapped the same shared file. If the file consists of counters, is it appropriate to use the Interlocked* functions (like InterlockedIncrement) to update those counters? Will those synchronize access across processes? Or do I need to use something heavier, like a mutex? Or perhaps the shared-memory mechanism itself ensures consistent views.

Was it helpful?

Solution

From MSDN:

...

The Interlocked API

The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. They also perform operations on variables in an atomic manner. The threads of different processes can use these functions if the variable is in shared memory.

So, yes, it is safe with your shared memory approach.

OTHER TIPS

The interlocked functions are intended for exactly that type of use.

From http://msdn.microsoft.com/en-us/library/ms684122.aspx:

The threads of different processes can use these functions if the variable is in shared memory.

Of course, if you need to have more than one item updated atomically, you'll need to go with a mutex or some other synchronization object that works across processes. There's nothing built-in to the shared memory mechanism to provide synchronization to access to the shared memory - you'll need to use the interlocked functions or a synchronization object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top