Reputation: 3637
I have a function that I want to run in different threads. The function populates a data structure, for example:
per_thread(int start_value, std::vector<SomeStruct>& reference)
{
for ( size_t i = 0; i < 500; i++ )
{
reference.push_back(func(i));
if (i == 2)
send_signal_back();
}
}
However, after this is done going through the loop some number of times, I want to start another thread, using this as the start value. Unfortunately, I don't understand how to send a signal back to the parent thread.
So I want something like this:
for( size_t j = 0; j < 5000; j += num_threads)
{
for (size_t i = 0; i < num_threads; i++)
{
std::async(per_thread(foo(j+i), std::ref(vec));
//wait for signal
}
}
How do I send such a signal?
Upvotes: 1
Views: 731
Reputation: 477120
I wouldn't use async
, because that's too high-level and does something else. (Here's a little rant of mine that touches on async
.)
It looks like you really just want threads and control them manually.
Try this:
#include <vector>
#include <thread>
std::vector<std::thread> threads;
for (std::size_t j = 0; j < 5000; j += num_threads)
{
for (std::size_t i = 0; i != num_threads; ++i)
{
threads.emplace_back(per_thread, foo(i + j), std::ref(vec));
}
}
for (auto & t: threads)
{
t.join();
}
This will finish once the longest-running thread has finished. (The "long-tail" effect.)
Upvotes: 4