Shared memory - requires synchronization

I saw a project in which communication between processes was performed using shared memory (for example, using ::CreateFileMappingWindows), and every time one of the processes wanted to report that some data was available in shared memory, a synchronization mechanism using these events notified the interested side that the contents of shared memory has changed.

What bothers me is the fact that for a process that reads new information, there are no corresponding memory latencies in order to know that it should cancel its copy of the data and read it from the main memory after its publication the production process.

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

EDIT I just wanted to add that after creating a file association, processes use the MapViewOfFile () API only once, and each new modification of the shared data uses the pointer received during the first call to MapViewOfFile () to read new data that is transferred via shared memory. Does proper synchronization require that every time the data is changed in shared memory, the process that reads the data must create MapViewOfFile () each time?

+3
source share
3 answers

If you use the Windows Named Event to change the alarm, then everything should be OK.

Process A modifies the data and calls SetEvent.

B WaitForSingleObject , , .

B . WaitForSingleObject , , , SetEvent, B.

, - SetEvent, , B .

, Mutex, CreateMutex, , Interlocked..., InterlockedExchange InterlockedIncrement.

, MapViewOfFile .

+3

, , InterlockedExchange. . msdn . :

( ) .

-. , 100% mutex- .

, , "" . "" , ( ), "" , - . , .., "" . :

#define LOCK_SET 1
#define LOCK_CLEAR 0

int* lock_location = LOCK_LOCATION; // ensure this is in shared memory
if (InterlockedExchange(lock_location, LOCK_SET) == LOCK_CLEAR)
{
    return true; // got the lock
}
else
{
    return false; // didn't get the lock
}

, , .

+2

Let process A process the data and process B the data consumer. So far, you have a mechanism for process A to notify process B that new data has been created. I suggest you create a return notification (B to A) that tells process A that the data has been used. If for performance reasons you do not want process A to wait for data to be consumed, you can configure the ring buffer into shared memory.

0
source

All Articles