Search topics...
Embedded LinuxIPCadvanced

How do you synchronize access to shared memory between processes?

0 upvotes
Practice with AISoon

Shared memory provides no built-in synchronization — two processes can read and write the same memory simultaneously, causing data races. You must add an explicit synchronization mechanism. The three main approaches are POSIX named semaphores, pthread mutexes in shared memory, and lock-free data structures.

POSIX named semaphores (sem_open, sem_wait, sem_post) are the simplest approach. They exist in the filesystem namespace (/dev/shm/sem.name), so both processes can open the same semaphore by name. Use a semaphore as a mutex (initialized to 1) to protect critical sections. The downside is that if a process crashes while holding the semaphore, it stays locked — there is no automatic cleanup. You need a watchdog or timeout mechanism (sem_timedwait) to recover.

Pthread mutexes with the PTHREAD_PROCESS_SHARED attribute can be placed directly in the shared memory region. This is more efficient than named semaphores (no filesystem lookup) and supports features like priority inheritance (PTHREAD_PRIO_INHERIT) to prevent priority inversion. The mutex must be initialized with pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED) and pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST) — the robust attribute is critical because it allows a surviving process to detect and recover when the mutex holder crashes (the next pthread_mutex_lock returns EOWNERDEAD, and the process calls pthread_mutex_consistent to reclaim it).

For the highest performance, lock-free ring buffers eliminate synchronization overhead entirely. A single-producer, single-consumer ring buffer needs only atomic load/store on the read and write indices — no mutexes, no system calls, no possibility of deadlock. This is the preferred pattern for high-throughput data streaming (audio, video, sensor data) between two processes. Multi-producer or multi-consumer scenarios require compare-and-swap (CAS) operations and are significantly more complex to implement correctly.

Source: Embedded Linux Q&A