C++11 C++;异步函数未异步启动
我试图异步启动一个函数,但它是同步启动的C++11 C++;异步函数未异步启动,c++11,asynchronous,promise,C++11,Asynchronous,Promise,我试图异步启动一个函数,但它是同步启动的 #include <thread> #include <future> #include <vector> #include <iostream> #include <algorithm> using namespace std; std::future<int> setPromise() { auto promise = std::make_shared<std:
#include <thread>
#include <future>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
std::future<int> setPromise()
{
auto promise = std::make_shared<std::promise<int>>();
auto future = promise->get_future();
auto asyncFn = [&]() {
cout << "Async started ...\n";
for(int i=0; i<100000; i++)
for(int j=0; j<10000; j++) {}
promise->set_value(400);
fprintf(stderr, "Async ended ...\n");
};
std::async(std::launch::async, asyncFn);
return future;
}
int main()
{
std::future<int> result = setPromise();
cout << "Asynchronously launched \n";
int ret = result.get();
cout << ret << endl;
return 0;
}
我希望lambda函数被异步调用,当循环在异步线程中运行时,我希望日志来自主线程。但是我看到函数从不异步启动,并且总是lambda完成,只有这样我们才能在main中执行下一个语句
我所期望的
Async started ...
Asynchronously launched
Async ended ...
我得到的是
Async started ...
Async ended ...
Asynchronously launched
它可能是异步运行的,只是很快就完成了 为了确定,您需要使日志记录竞争条件为自由 类似这样的事情(只是想法):
std::future setPromise()
{
std::atomic_flag canGo=atomic_flag_INIT;
自动异步fn=[&]{
而(!canGo);
日志(“异步启动…”);//也使用线程安全日志
...
}
std::async(std::launch::async,asyncFn);
日志(“放手…”);
canGo.test_和_set();
...
}
另外请注意,
iostream
不是线程安全的,因此在进行实验时最好使用线程安全的记录器。它可能是异步运行的,只是很快就完成了
为了确定,您需要使日志记录竞争条件为自由
类似这样的事情(只是想法):
std::future setPromise()
{
std::atomic_flag canGo=atomic_flag_INIT;
自动异步fn=[&]{
而(!canGo);
日志(“异步启动…”);//也使用线程安全日志
...
}
std::async(std::launch::async,asyncFn);
日志(“放手…”);
canGo.test_和_set();
...
}
另外请注意,iostream
不是线程安全的,所以在进行实验时最好使用线程安全的记录器。通过在下面的行中调用
std::async(std::launch::async, asyncFn);
创建临时的future
对象,其析构函数仅在async
启动的任务完成时结束。因此,在setPromise
函数作用域的末尾,它的执行被阻止,直到作业-asyncFn
结束
您可以阅读有关future destrcutor的行为,以及当future的共享状态未就绪时会发生什么。请在下面的行中调用
std::async(std::launch::async, asyncFn);
创建临时的future
对象,其析构函数仅在async
启动的任务完成时结束。因此,在setPromise
函数作用域的末尾,它的执行被阻止,直到作业-asyncFn
结束
您可以阅读有关行为future destrcutor以及当future的共享状态未就绪时会发生什么情况。+1实际上,
std::async
生成的隐式future根本没有使用,而您设置的结果与lambda本身不同。更好的方法是autoasyncfn=[&](){…return400;};返回std::async(std::launch::async,asyncFn)代码>将按预期工作。+1,实际上根本不使用由std::async
生成的隐式未来,而您设置的结果与lambda本身不同。更好的方法是autoasyncfn=[&](){…return400;};返回std::async(std::launch::async,asyncFn)代码>将按预期工作。
std::async(std::launch::async, asyncFn);