proper way of handling std::thread termination in child process after fork()

荒凉一梦 提交于 2020-05-13 14:45:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!