简体   繁体   English

线程构建块会在fork上克隆线程

[英]Threading Building Blocks clones threads on fork

For starting another program I use fork() and exec() in my code. 为了启动另一个程序,我在代码中使用了fork()和exec()。 Since my program uses the Threading Building Blocks library for task management it initializes the scheduler with a thread pool before. 由于我的程序使用线程构建基块库进行任务管理,因此它之前使用线程池初始化了调度程序。

Whenever I do a fork it seems that all the threads are being forked too (checked the number of threads with top). 每当我进行分叉时,似乎所有线程也都被分叉了(检查顶部的线程数)。 From what I've read on the Internet only the current thread should be forked. 根据我在Internet上阅读的内容,仅应分叉当前线程。

How do I achieve this behaviour and is the Threading Building Blocks causing the fork of multiple threads? 我如何实现此行为,并且线程构建块是否导致多个线程分叉?

I believe the Internet is correct in this regard, ie right after fork a newly created process has only single thread, one that called fork. 我相信互联网在这方面是正确的,即在fork之后,一个新创建的进程只有一个线程,一个称为fork的线程。 Problem with fork in multithreaded program is state integrity for other (not doing fork) threads, ie if a lock is taken during fork, it must be untaken in both processes, new and old. 多线程程序中fork的问题是其他(不执行fork)线程的状态完整性,即,如果在fork期间获取了锁,则无论新旧进程都必须取消锁定。 TBB has some support for dealing with it, but I'm not sure this is what you need, as exec right after fork is replacing all memory, so taken locks must be not an issue. TBB对此有一些支持,但是我不确定这是否是您所需要的,因为在fork之后的exec正在替换所有内存,因此采用锁定绝对不是问题。

If you are doing something special (say, taking a lock possibly locked by TBB workers) between fork and exec, than 1st obstacle with TBB is state of workers. 如果您在前叉和执行杆之间执行一些特殊的操作(例如,采取可能由TBB工人锁定的锁),那么TBB的第一个障碍就是工人的状态。 TBB allows you to wait till workers termination (note this is preview functionality). 使用TBB,您可以等到工人解雇为止(请注意,这是预览功能)。

#define TBB_PREVIEW_WAITING_FOR_WORKERS 1
#include "tbb/task_scheduler_init.h"
{
    tbb::task_scheduler_init sch(threads, 0, /*wait_workers=*/true);
    tbb::parallel_for(…);
} // wait workers here, no worker threads after this point

Without this special argument to task_scheduler_init(), there is no guarantee for workers termination. 如果没有task_scheduler_init()的这个特殊参数,就不能保证终止工作。

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

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