Despite the citations that others have made to documentation, the classes std::mutex
and std::shared_mutex
actually do work across processes when used in shared memory on Linux. I've checked with GCC 8.3.1 and Clang 6.0.1.
Standard C++ implementations of these on Linux use pthreads. The pthreads provision of PTHREAD_PROCESS_SHARED
and PTHREAD_PROCESS_PRIVATE
as attributes for pthread_mutex_t
and pthread_rwlock_t
are abstracted out and defaulted
by std::mutex
and std::shared_mutex
. Even though POSIX documentation says that the default is PRIVATE, a pthread_mutex_t
and pthread_rwlock_t
allocated in shared memory will block competing processes when locked. This is because the actual implementation of pthreads on Linux uses futexes, and they are intended for use in shared memory even in cases where mapped addresses may differ across processes.
It's possible that the PTHREADS_PROCESS_PRIVATE behaviour is actually more difficult to implement given the strategy of using futexes to implement mutexes, and as such, is silently not implemented.
If you did want your mutexes to be process-private, just avoid putting them in shared memory. On the other hand if you do want to share them, be cautious that this standards discrepancy could be subject to change.
For reliability, use Boost Interprocess.
std::mutex
is the correct primitive to use here, it might use process-specific data (to help with inter-thread synchronization). You should procably use your platforms cross-process mutex or semaphore instead. – Viscosity