在fork()之后子进程中处理std :: thread终止的正确方法 [英] proper way of handling std::thread termination in child process after fork()

查看:530
本文介绍了在fork()之后子进程中处理std :: thread终止的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽可能多地皱着眉,我还是要去做:)

Frown as much as you want, I'm going to do it anyway :)

我的问题是:在下面的代码中,由fork()生成的子过程中处理std::thread终止的正确方法是什么? std::thread::detach()std::thread::join()?

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;
}

我知道只有调用fork()的线程是重复的,这意味着std::thread实际上在子进程中什么也不做,对吗?因此,我对此表示怀疑.

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.

推荐答案

根据fork

According to fork description, the proper way is to call t.join() only from parent process, as child one only replicates caller thread.

还请注意,多线程程序中的子进程仅允许调用可用于信号处理程序和exec的函数.

Note also, that child process in multithreaded program is allowed only to call functions available for signal handlers and exec.

这篇关于在fork()之后子进程中处理std :: thread终止的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆