views:

231

answers:

2

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.

+3  A: 

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.

Michael Burr
But does InterlockedIncrement work *cross-process*? I think that's the relevant question--and to the best of my knowledge, it does not.
JSBangs
From http://msdn.microsoft.com/en-us/library/ms683614.aspx: "This function generates a full memory barrier (or fence) to ensure that memory operations are completed in order."
Michael Burr
As long as the memory is mapped to the same physical address, Interlocked is fine. It results in making sure the memory bus is locked for all processors and their caches coherent for the given address, nothing having to do with processes.
Freed
I guess what wasn't clear to me is whether the file mappings always result in the memory being mapped to the same physical address or if the OS copies data around to make it look that way. With all the layers (virtual address, view, mapping, physical address, and file), it's never been clear to me where the merge point was. The shared memory sections in MSDN make some comments about coherence guarantees only if you use the same (or duplicated) mapping handle.
Adrian McCarthy
Under the hood any mutexes stored in shared memory that you would use are making use of the same memory fences and lock instructions that Interlocked* uses.
Joseph Garvin
A: 

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 save with your shared memory approach.

Frank Bollack