Preamble
The marked "dupe" above does not answer my question, as it involves the safety of forking with threads in use. I am not generating threads in my code, and am more concerned with the validity of pthread_mutex_t
structs and their internals registered with the OS when a fork()
occurs. ie: Are the mutexes re-created on fork()
within the child process, or do children just have a valid (or invalid) shallow copy of the parent's mutex internals?
Background
I have an audio/hardware handling library that wraps some DSP functions with a simple API using a recursive pthread_mutex_t
. The reason it is a recursive mutex is because some API functions call other API functions in turn, and I want to make sure only a single thread ever enters the critical section per instance of the library. So, the code would look like so:
static pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
void read() {
pthread_mutex_lock(&mutex);
// ...
pthread_mutex_unlock(&mutex);
}
void write() {
pthread_mutex_lock(&mutex);
// ...
pthread_mutex_unlock(&mutex);
}
void toggle() {
pthread_mutex_lock(&mutex);
read();
// ...
write();
pthread_mutex_unlock(&mutex);
}
Question
If a user application uses my library, and the application issues the fork()
call, does the child process's instance of my library need to have its instance of the mutex re-initialized? I know child processes don't inherit threads, and a specific mutex initialization flag needs to be used if I want the two processes to truly share the mutex (can't recall what the flag is) or I have to make use of mmap
IIRC. But is the mutex instance used by the child valid (ie: does fork()
duplicate the internal values, but they aren't valid anymore, or is a new mutex initialized with the OS)? I don't want the child and parent process to share a mutex when a fork()
occurs, but I want to make sure the client is using a valid mutex handle.
Note: I can guarantee that the mutex will not be locked when the fork()
call is issued.
Thank you.