Reputation: 1226
C++11
int main(int argc, char** argv) {
std::async(std::launch::async, [](){
while(true) cout << "async thread" <<endl;
});
while(true) cout << "main thread" << endl;
return 0;
}
I expected the output should be something interleaved with async thread
and main thread
since there should be 2 different threads.
But it's not.
It outputs:
async thread
async thread
async thread
async thread
...
I guess there's only one thread. Can someone tell me why it isn't spawn a new thread for std::async
? Thanks.
Upvotes: 2
Views: 2554
Reputation: 1226
Change to this:
auto _ = std::async(std::launch::async, [](){
while(true) cout << "async thread" <<endl;
});
Document:
If the std::future obtained from std::async is not moved from or bound to a reference, the destructor of the std::future will block at the end of the full expression until the asynchronous operation completes, essentially making code such as the following synchronous:
std::async(std::launch::async, []{ f(); }); // temporary's dtor waits for f() std::async(std::launch::async, []{ g(); }); // does not start until f() completes
Upvotes: 6