簡體   English   中英

當我使用異步任務(std::async Function 模板)時,我應該尊重指令的順序嗎?

[英]Should i respect the order of instructions when i'm using Asynchronous tasks (std::async Function Template)?

當我遇到一個案例時,我正在開發一個多線程程序,當我詢問一些異步實現時,如下所示:

#include <iostream>
#include <thread>
#include <chrono>
#include <future>

using namespace std::chrono;

int increment(int i){
     i++;
     std::this_thread::sleep_for(seconds(5));

     return i;
}

int main()
{

    int x(0),y(0);

    std::future<int> result = std::async(std::launch::async,
                                         [](int i)mutable throw()->
                                         int{
                                              i++;
                                              std::this_thread::sleep_for(seconds(5));
                                              return i;
                                          }, y);
    x=increment(x);
    y = result.get();
    return 0;

}

關注x=increment(x)y = result.get()這兩條指令應該是這個順序,還是有別的解釋? 因為:

情況1:

x=increment(x);
y = result.get();

執行時間:5 秒(如預期!)

案例二:

y = result.get();
x=increment(x);

執行時間:10秒

對此有什么合乎邏輯的解釋嗎?

y = result.get();
x=increment(x);

在這種情況下,主線程將被阻塞,直到創建的線程完成它的工作,因為get阻塞它正在工作的線程,直到它完成它的工作

x=increment(x);
y = result.get();

這里沒有阻塞,因為y = result.get(); 最后出現,這種方式是線程應該工作的方式。

請參閱https://en.cppreference.com/w/cpp/thread/future/get

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM