Linux shared memory synchronization

I have implemented two applications that exchange data using the POSIX shared memory API (i.e. shm_open ). One process updates data stored in a shared memory segment, and another process reads it. I want to synchronize access to an area of ​​shared memory using a kind of mutex or semaphore. What is the most efficient way to do this? Some of the mechanisms that I consider are

  • POSIX mutex stored in the shared memory segment (setting of the PTHREAD_PROCESS_SHARED attribute is required)
  • Creating a System V semaphore with semget
+7
source share
4 answers

Instead of the System V semaphore, I would go with a POSIX semaphore called sem_open() , etc.

+2
source

It is also possible to make this an answer.

You can use sem_init with pshared true to create a POSIX semaphore in your shared memory space. I have successfully used this in the past.

As for whether it is faster or slower than the general mutex and condition variable, only profiling can tell you. On Linux, I suspect that they are all very similar, as they rely on the "futex" mechanism.

+1
source

If efficiency is important, I would go with mutexes and process state variables.

AFAIR, syscall is required for each semaphore operation, so an invalid mutex should be faster than the [ab] semaphore used in a mutex-like image.

0
source

Firstly, it is really a guideline to know if performance is important. The cost of these things is often overestimated. Therefore, if you do not find that access to the control structure is in the same order of magnitude as the records, just take any construct semantically best for your use case. That would be common if you had 100 bytes to access the management structure.

Otherwise, if the management structure is a bottleneck, you may not need to use them. C11 has a new concept of _Atomic types and operations, which can be used in cases where there are races in data access. C11 is not yet widely implemented, but probably all modern compilers have extensions that already implement these functions.

0
source

All Articles