Reputation: 23
I need a little help i'm using "thread" library in C++, I want to start three threads together, thread 1 and 2 have to compute data, and i want to start third thread after finish previous. Please about example.
I have to start 3 thread, the third one must be blocked on start and wait after previous finish their job
#include <thread>
void one() { /* ... */ }
void two() { /* ... */ }
void three() {
//this one is blocked on start and waiting for finish previus
}
void f()
{
std::thread t1(one), t2(two), t3(three);
t1.join();
t2.join();
t3.join();
}
Upvotes: 1
Views: 1112
Reputation: 376
The other answers should suffice unless your application keeps running (or is a background process). That's the information missing in your question.
However if above is the case then this is how you would go about:
Your first two threads will wake up and start working when some data is made available. Once it has computed the required data, it will send a message to the third thread. Depending on what the third thread is doing, it will either immediately start working on the message or queue it up so that it can work on it later.
So, in this scenario, the key is messaging and queuing.
Upvotes: 1
Reputation: 302942
A thread starts as soon as it's constructed with a functor. So if you don't want to start three()
until the first two are done, you just have to delay construction:
void f()
{
std::thread t1(one), t2(two);
t1.join();
t2.join();
// ok, 1 and 2 are done, start 3
std::thread t3(three);
t3.join();
// all 3 are done
}
If you really want to start the thread and block until t1/t2 finish, then you want to do something like:
void f()
{
std::condition_variable cv;
std::mutex m;
std::thread t1(one), t2(two);
std::thread t3([&]{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk);
three();
});
t1.join();
t2.join();
// ok, 1 and 2 are done, start 3
{
// I don't think the lock here is strictly necessary
std::unique_lock<std::mutex> lk(m);
cv.notify_all();
}
t3.join();
// all 3 are done
}
Upvotes: 1
Reputation: 5871
You guys know your threads, but you didn't read the question. He didn't say anything about shutting down the main program until all the threads finished. It's just t3 which has to wait.
The code should start t3 only. t3 should start t1 and t2 wait on them with t1.join();t2.join(); then execute its code.
Upvotes: 0
Reputation: 465
What you want to do is join the first two threads, and then kick of the third one when that instruction is finished. You can see a good example of this here
Upvotes: -1
Reputation: 477040
Don't start a third thread. Just continue in the calling thread after the two worker threads finish:
#include <thread>
void do_work() { /* ... */ }
void f()
{
std::thread t1(do_work), t2(do_work);
t1.join();
t2.join();
// do final work here
}
Upvotes: 1