C++ std::async 不生成新线程
C++ std::async does not spawn a new thread
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;
}
我预计输出应该与 async thread
和 main thread
交错,因为应该有 2 个不同的线程。
但事实并非如此。
它输出:
async thread
async thread
async thread
async thread
...
我想只有一个线程。有人能告诉我为什么它没有为 std::async
生成新线程吗?谢谢。
改为:
auto _ = std::async(std::launch::async, [](){
while(true) cout << "async thread" <<endl;
});
文件:
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
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;
}
我预计输出应该与 async thread
和 main thread
交错,因为应该有 2 个不同的线程。
但事实并非如此。
它输出:
async thread
async thread
async thread
async thread
...
我想只有一个线程。有人能告诉我为什么它没有为 std::async
生成新线程吗?谢谢。
改为:
auto _ = std::async(std::launch::async, [](){
while(true) cout << "async thread" <<endl;
});
文件:
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