问题
I have a scenario where the shared memory area is exclusively accessed by two different processes. When I launch the processes, the first process successfully locks the mutex, updates the memory and unlock the mutex. But I observe that when the second process try to lock it, it is still in deadlock state, waiting for mutex to unlock.
Time difference between the mutex lock is 10s for first and second process.
I am using the std::mutex. Please tell me what I am missing.
回答1:
An std::mutex instance is only scoped to a single process; it is not capable of interprocess synchronization/concurrency. It is only capable of synchronizing child threads within a parent process.
Look to use Boost or an interprocess synchronization library instead.
回答2:
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.
回答3:
std::mutex does not support interprocess operation but pthread library has interprocess mutex that you can use. Example here.
来源:https://stackoverflow.com/questions/46662935/stdmutex-in-shared-memory-not-working