P
P
pixik2015-11-16 13:29:49
C++ / C#
pixik, 2015-11-16 13:29:49

How can a program wait for all std::thread threads to complete before exiting a function?

Good time!
I have 2 objects based on which, by composition, std::thread is encapsulated.
The program needs to start both threads and wait until they complete. When I execute:

somethread t1, t2;
t1.start();
t2.start();
t1.join();
t2.join();
// some work
exit();

then only t1 is attached to the main thread, and t2 by itself.
In Williams' book "Parallel C++ Programming", I read about thread_guard, something like thread guard, where in the destructor join () is performed on the guarded thread and waits until the thread ends. But perhaps there are some standard std::* tools that allow you to do this.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg Tsilyurik, 2015-11-16
@pixik

then only t1 is attached to the main thread, and t2 by itself.
It is not at all clear what this phrase could mean?
No one "binds" to anyone, and pthraed_join() (which is what all your std::thread or boost::thread are built on) just waits for the joined (created in the PTHREAD_CREATE_JOINABLE state) thread to complete.
You just have a mistake in the architecture of a hypothetical application, and confusion in your head (regarding threads).

I
iv_k, 2015-11-16
@iv_k


Do you not need the option with a boost ?
boost::thread_group g;
g.create_thread(boost::bind(&t1));
g.create_thread(boost::bind(&t2));
// multiply threads as much as you want, you can in the loop
g.join_all();
// wait until everything is finished

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question