Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Shared Memory Synchronization

I have implemented two applications that share data using the POSIX shared memory API (i.e. shm_open). One process updates data stored in the shared memory segment and another process reads it. I want to synchronize the access to the shared memory region using some sort of mutex or semaphore. What is the most efficient way of do this? Some mechanisms I am considering are

  • A POSIX mutex stored in the shared memory segment (Setting the PTHREAD_PROCESS_SHARED attribute would be required)
  • Creating a System V semaphore using semget
like image 488
waffleman Avatar asked Jan 16 '13 17:01

waffleman


2 Answers

Rather than a System V semaphore, I would go with a POSIX named semaphore using sem_open(), etc.

like image 143
Jason Avatar answered Nov 11 '22 21:11

Jason


Might as well make this an answer.

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

As for whether this is faster or slower than a shared mutex and condition variable, only profiling can tell you. On Linux I suspect they are all pretty similar since they rely on the "futex" machinery.

like image 21
Nemo Avatar answered Nov 11 '22 23:11

Nemo