std::async中的奇怪行为
Strange behaviour in std::async
我想有一个任务,如果它运行时间不够,可以被杀死。
所以我在尝试这个:
#include <iostream>
#include <future>
using namespace std;
int main()
{
auto handle = std::async(std::launch::deferred,[]
{
cout<<"Initializing thread..."<<endl;
this_thread::sleep_for(std::chrono::seconds(5));
}
);
cout<<"Starting..."<<endl;
handle.wait_for(std::chrono::seconds(2));
cout<<"Finished correctly"<<endl;
return 0;
}
输出:
开始……
正确完成
为什么不打印"初始化线程"?我尝试交换两个chronos和不工作无论如何
您从不要求任务的结果,因此它不被调度。
将deferred
替换为async
,您将得到您所期望的
deferred
仅对非定时wait
函数求值。如果更改为:
handle.wait();
相关文章:
- 为什么std::async使用同一个线程运行函数
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 使用 std::async 时死锁,将来作为成员
- 为什么我不能将引用作为 std::async 的函数参数传递
- std::async from std::async in windows xp
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- std::async 不会立即调用
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 在Visual Studio中,与std::async一起使用时不调用"thread_local"变量"析构函数,这是一个错误吗?
- 可能的 std::async 实现错误 Windows
- C++从 std::async 函数读取命名空间中的全局变量标志
- std::async 究竟是如何执行的?
- 使用 g++8 和 c++20 的 std::async 编译问题
- 如何有效地使用 std::async 对指针数组执行操作
- 标准C++11是否保证std::async(std::launch::asyncfunc)在单独的线程中启动func
- 何时需要使用std::async(std::launch::asyncfunc())而不是func(()
- std::async([](){ std::cout<< "Hello " ; }) build error
- GCC 的行为与 std::async(std::launch::async) 与 Clang 的行为
- std::async - std::launch::async | std::launch::deferred