Reputation: 1342
For starting another program I use fork() and exec() in my code. 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.
How do I achieve this behaviour and is the Threading Building Blocks causing the fork of multiple threads?
Upvotes: 2
Views: 499
Reputation: 578
I believe the Internet is correct in this regard, i.e. right after fork a newly created process has only single thread, one that called fork. Problem with fork in multithreaded program is state integrity for other (not doing fork) threads, i.e. if a lock is taken during fork, it must be untaken in both processes, new and old. 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.
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 allows you to wait till workers termination (note this is preview functionality).
#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.
Upvotes: 3