int
main()
{
std::mutex io;
std::vector<std::future<void>> futures;
std::cout << "Main id: " << std::this_thread::get_id() << std::endl;
for (int i = 0; i < 12; ++i) {
std::future<void> f = std::async(std::launch::async, [&]{
std::this_thread::sleep_for(std::chrono::seconds(10));
io.lock();
std::cout << "Thread id: " << std::this_thread::get_id() << std::endl;
io.unlock();
});
futures.push_back(std::move(f));
}
for (auto& f : futures) {
f.wait();
}
}
I have read on several blogs that I can not use async
for task based concurrency because it doesn't distribute tasks
evenly on the threads, so I created a small test program.
Main id: 140673289357120
Thread id: 140673241089792
Thread id: 140673215911680
Thread id: 140673232697088
Thread id: 140673224304384
Thread id: 140673207518976
Thread id: 140673199126272
Thread id: 140673165555456
Thread id: 140673190733568
Thread id: 140673173948160
Thread id: 140673182340864
Thread id: 140673157162752
Thread id: 140673148770048
But the output is not something that I expected. My machine has 2 cores with hyper-threading which gives me 4 threads, but looking at the thread ids it seems that they are all unique.
Can async be used for task based concurrency?
What exactly does this_thread::get_id()
return?
By task based concurrency I mean that the work will be split evenly between all available threads.