Let's say we have a process with two threads. One thread does some work on some shared resource and periodically takes out a scoped lock on a boost::interprocess::mutex. The other thread causes a fork/exec, at some random time.
Thread 1
void takeLockDoWork() {
using namespace boost::interprocess;
managed_shared_memory segment(open_only, "xxx");
interprocess_sharable_mutex *mutex = segment.find<interprocess_sharable_mutex>("mymutex").first;
scoped_lock<interprocess_sharable_mutex> lock(*mutex);
// access or do work on a shared resource here
//lock automatically unlocks when scope is left.
}
Let's say Thread 2 forks right after the scoped_lock is taken out. Presumably the child process has the same lock state as the parent.
What happens? Will there now be a race condition with the parent process?
As long as you don't fork from a thread that is holding an interprocess_sharable_mutex
or access memory that was being protected by a mutex, you're okay.
The mutex exists in shared memory, meaning that even though you forked, the mutex state wasn't duplicated; it exists in one place, accessible by both processes.
Because forking only maintains the forking thread in the child, only the other thread in the parent thinks it has ownership of the mutex, so there's no problem. Even if you tried to acquire the mutex after forking, you would still be okay; it would just block until the parent releases it.