☑ Sharing pthreads locks between processes

How to share pthreads primitives across processes.

share tomatoes

The POSIX threads library has some useful primitives for locking between multiple threads, primarily mutexes and condition variables.

Typically these are only effective to lock between threads within the same process. However, pthreads defines a PTHREAD_PROCESS_SHARED attribute for both of these primitives which can be used to specify that they should also be used between processes.

This attribute simply indicates that the primitives be used in a way which is compatible with shared access, however — application code must still arrange to store them in shared memory. This is fairly easily arranged with an anonymous mmap(), or shmget() and shmat() if your processes don’t have a parent/child relationship.

The use of shared memory makes things a little more complicated, which is disappointing, but it still seems to me that using these primitives to synchronise processes is probably still a little more elegant than using pipes or something similar (even if that’s probably a little more portable).

I’ve added a code example to my wiki which illustrates this. I’ve used an anonymous mmap() for shared memory — the previous revision of the page used System V shared memory, but since this isn’t cleaned up automatically on application exit then the mmap() approach is safer.

31 Jan 2013 at 1:02PM by Andy Pearce in Software  | Photo by Elaine Casap on Unsplash  | Tags: pthreads  linux  ipc posix