问题
Frown as much as you want, I'm going to do it anyway :)
My question is: in the following code, what is the proper way to handle the termination of the std::thread
in the subprocess generated by fork()
? std::thread::detach()
or std::thread::join()
?
#include <thread>
#include <iostream>
#include <unistd.h>
struct A {
void Fork()
{
std::thread t(&A::Parallel, this);
pid_t pid = fork();
if(pid) {
//parent
t.join();
} else {
//child
t.join(); // OR t.detach()?
}
}
void Parallel()
{
std::cout << "asd" << std::endl;
}
};
int main() {
A a;
a.Fork();
return 0;
}
I know that only the thread that calls fork()
is duplicated, which means that the std::thread
is actually doing nothing in the child process right? Hence my doubt.
回答1:
According to fork
description, the proper way is to call t.join()
only from parent process, as child one only replicates caller thread.
Note also, that child process in multithreaded program is allowed only to call functions available for signal handlers and exec
.
来源:https://stackoverflow.com/questions/31746439/proper-way-of-handling-stdthread-termination-in-child-process-after-fork