[英]Should i respect the order of instructions when i'm using Asynchronous tasks (std::async Function Template)?
I was working on a multi-threaded program when I crossed a case in which when I ask some asynchronous implementations like the following:当我遇到一个案例时,我正在开发一个多线程程序,当我询问一些异步实现时,如下所示:
#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;
}
Focusing on the two instructions x=increment(x)
and y = result.get()
should they be in this order, or is there another explanation?关注x=increment(x)
和y = result.get()
这两条指令应该是这个顺序,还是有别的解释? Because:因为:
Case 1:情况1:
x=increment(x);
y = result.get();
Time Execution: 5 seconds (As expected !)执行时间:5 秒(如预期!)
Case 2:案例二:
y = result.get();
x=increment(x);
Time Execution: 10 seconds执行时间:10秒
Is there any logical explanations to this?对此有什么合乎逻辑的解释吗?
y = result.get();
x=increment(x);
In this case, the main thread will be blocked until the created thread finishes its work because get
block the thread where it's working until it finishes its work在这种情况下,主线程将被阻塞,直到创建的线程完成它的工作,因为get
阻塞它正在工作的线程,直到它完成它的工作
x=increment(x);
y = result.get();
Here is no blocking because y = result.get();
这里没有阻塞,因为y = result.get();
comes at the end and this way is the way threads should work.最后出现,这种方式是线程应该工作的方式。
See https://en.cppreference.com/w/cpp/thread/future/get请参阅https://en.cppreference.com/w/cpp/thread/future/get
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.