How to share pthreads primitives across processes.
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 as a GitHub Gist which illustrates this.
I’ve used an anonymous mmap()
for shared memory—previously I’d used System V shared memory, but since this isn’t cleaned up
automatically on application exit then the mmap()
approach is safer.
2025 UPDATE: I wrote this article back in 2013 when my blog didn’t format code snippets very well, but since then the link above to the code snippet became broken. I’ve updated it to point to a Gist, which should be quite persistent, but since this blog also formats code better now, here’s the same code inline.
If you want to see the difference that the mutex makes, just comment out pthread_mutex_lock()
and pthread_mutex_unlock()
in child_loop()
and compare the final counter value to when they’re included.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
|