![](/img/trans.png)
[英]behaviour of std::async(std::launch::deferred) + std::future::then
[英]std::async and std::future behaviour
我試圖了解異步行為,並寫了一些愚蠢的測試程序。
int f(int i)
{
std::cout << i << ": hello" << std::endl;
int j = 0;
while (j < 10000) //just add some delay
{
j++;
}
return j;
}
int main()
{
for (int i = 0; i < 10000; i++)
{
std::async(std::launch::async, f, i);
}
std::cout << "in main" << std::endl;
}
使用上面的代碼,輸出似乎完全同步。 所有10000個線程似乎按順序執行。 主線程塊。
0: hello
1: hello
2: hello
.......
10000: hello
in main
但是,當返回的未來存儲在向量中時,輸出將全部損壞並且主要退出而不等待生成的線程。 線程是否在此處分離?
int main()
{
std::vector<std::future<int>> v;
for (int i = 0; i < 10000; i++)
{
v.push_back(std::move(std::async(std::launch::async, f, i)));
}
std::cout << "in main" << std::endl;
}
輸出:
2: hello3: hello
46: hello
: hello5: hello
9: hello
10: hello
11: hello
最后,嘗試在返回的未來使用get()仍然會提供類似的錯位輸出:
int main()
{
std::vector<std::future<int>> v;
for (int i = 0; i < 10000; i++)
{
v.push_back(std::move(std::async(std::launch::async, f, i)));
}
for (int i = 0; i < 10000; i++)
{
std::cout << v[i].get();
}
std::cout << "in main" << std::endl;
}
輸出:
3: hello
4: hello
1: hello
5: hello
0: hello
2: hello
我想在第一種情況下,主要將退出而不等待在后台運行的線程。 至少在第三種情況下,main將阻止future.get()。
引擎蓋下究竟發生了什么?
異步返回的期貨在他們的dtor中隱含地執行.wait()
,但是:這種行為可以move
。
這解釋了你的所有症狀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.