简体   繁体   English

在fork()之后子进程中处理std :: thread终止的正确方法

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

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() ? 我的问题是:在以下代码中,处理fork()生成的子std::threadstd::thread终止的正确方法是什么? std::thread::detach() or std::thread::join() ? std::thread::detach()还是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? 我知道只有调用fork()的线程是重复的,这意味着std::thread实际上在子进程中什么也不做,对吗? Hence my doubt. 因此,我对此表示怀疑。

According to fork description , the proper way is to call t.join() only from parent process, as child one only replicates caller thread. 根据fork 描述 ,正确的方法是仅从父进程调用t.join() ,因为子进程仅复制调用者线程。

Note also, that child process in multithreaded program is allowed only to call functions available for signal handlers and exec . 还要注意,多线程程序中的子进程仅允许调用可用于信号处理程序和exec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM