c++ - 当我使用异步任务(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()
应该是这样的顺序,还是有其他解释?因为
情况一:
x=increment(x);
y = result.get();
执行时间: 5秒(如预期的那样!)。
情况2:时间执行:5秒(如预期!)。
y = result.get();
x=increment(x);
时间执行:10秒
有什么逻辑上的解释吗?
【回答】:
y = result.get();
x=increment(x);
在这种情况下,主线程将被阻塞,直到创建的线程完成其工作,因为 get
封锁正在工作的线程,直到它完成工作。
x=increment(x);
y = result.get();
这里没有阻挡,因为 y = result.get();
在最后才会出现,这种方式才是线程应有的工作方式。