How should I reinitailize or unlock the std::mutex in child process, so that it does not blocked?
I think that the key issue might be about a mutex was locked in the parent process at the time of forking, and then it will appear as locked in the child as well.
Maybe try to use POSIX pthread_atfork with pthread_mutex instead of fork (refer to Linux/UNIX system: pthread_atfork). The mechanism allows to register handlers to prepare and restore mutexes during a fork().
The intent of pthread_atfork() was to provide a mechanism whereby the application (or a library) could ensure that mutexes and other process and thread state would be restored to a consistent state. In practice, this task is generally too difficult to be practicable.
Here’s a simple example:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void prepare() {
pthread_mutex_lock(&mutex);
}
void parent() {
pthread_mutex_unlock(&mutex);
}
void child() {
pthread_mutex_unlock(&mutex);
}
int main() {
pthread_atfork(prepare, parent, child);
if (fork() == 0) {
// Child process
pthread_mutex_lock(&mutex);
std::cout << "Child acquired the lock" << std::endl;
pthread_mutex_unlock(&mutex);
std::cout << "Child released the lock" << std::endl;
} else {
// Parent process
pthread_mutex_lock(&mutex);
std::cout << "Parent acquired the lock" << std::endl;
// execute some tasks
pthread_mutex_unlock(&mutex);
std::cout << "Parent released the lock" << std::endl;
}
return 0;
}
Hope this is helpful in resolving this issue.