Yve*_*ves 6 c++ multithreading future promise c++11
#include <iostream>
#include <string>
#include <thread>
#include <future>
int main()
{
auto pms = std::promise<std::string>();
auto ftr = pms.get_future();
std::thread([&](){pms.set_value("hello world");});
ftr.wait();
std::cout << ftr.get() << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据此链接,std::future::wait阻止直到结果变得可用.
但是,上面的代码无法打印任何内容.显然主线程已在完成线程之前pms.set_value完成.
为什么不ftr.wait()阻止?
问题不是std::future::wait没有阻止.真正的问题是,在您生成的线程,执行它的工作以及std::thread主线程中(临时)对象的销毁之间存在竞争条件.
因此,如果线程仍然可以连接,abort则在析构函数中调用std::thread.
工作代码:
#include <iostream>
#include <string>
#include <thread>
#include <future>
#include <chrono>
int main()
{
auto pms = std::promise<std::string>();
auto ftr = pms.get_future();
std::thread thread ([&](){pms.set_value("hello world");});
ftr.wait();
std::cout << ftr.get() << std::endl;
thread.join ();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
注意,如果你没有thread明确加入,你仍然会有相同的竞争条件(因为它main可以更快地完成它的工作,因为它thread可以自我清理.
演示工作示例:这里.
| 归档时间: |
|
| 查看次数: |
1539 次 |
| 最近记录: |