I have a Linux program which spawns several processes (fork) and communicates through POSIX Shared Memory. I’d like to have each process allocate an id (0-255). My intention is to place a bitvector in the shared memory region (initialized to zero) and atomically compare and swap a bit to allocate an id.
Is there a c++11-friendly way to do this? Can I create an atomic bitset? Can I use a mutex across processes? How do I assure that constructors get called once and only once across all processes?
The C++11 threading primitives (mutexes, atomics, etc) are threading primitives. The C++ standard doesn’t reference processes, and most of these tools don’t interoperate across processes.
The only mention of processes in the standard is in a non-normative notation that says that lock-free atomics are intended to be OK for IPC:
Outside of this non-normative notation, the threading primitives are not intended to be a means of achieving inter-process communication. The behavior of such objects when placed in shared memory (aside from lock-free atomics as noted above) is undefined.