为什么 future::wait() 块
Why doesn't future::wait() block
#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;
}
根据此链接, std::future::wait
块直到结果可避免。
但是,上面的代码无法打印任何内容。显然,主线程在pms.set_value
的线程完成之前已经完成。
为什么不 ftr.wait()
块?
问题不是std::future::wait
没有阻止。真正的问题是,您在产生的线程,进行工作的线程和主线程中的std::thread
(临时)对象的破坏之间有种族条件。
因此,如果该线程仍然可加入,则在std::thread
的灾难中调用abort
。
工作代码:
#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;
}
注意,如果您不明确地加入thread
,则您仍然具有相同的种族条件(因为main
可能可以比thread
更快地完成工作。
工作的演示示例:此处。
或者您可以分离线程并使用promise::set_value_at_thread_exit
而不是set_value
#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([&](){pms.set_value_at_thread_exit("hello world");}).detach();
ftr.wait();
std::cout << ftr.get() << std::endl;
return 0;
}
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- 架构决策:返回std::future还是提供回调
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- std::memory_order for std::atomic:<T>:wait
- 使用用户定义的参数调用future/async并调用类方法
- std::p romise::set_value() 和 std::future::wait() 是否提供内存围栏?
- 修改在 std::future 的 lambda 中引用捕获的值
- 从 T 创建 std::future 的最佳方式<T>
- C++ std::future没有被调用
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 如何使用 boost::future 重新抛出 std::exception_ptr 存储的原始异常?
- Make zmqpp::socket::connect a std::future
- std::future可以比std::promise活得更长吗
- std::future::get()或std::future::wait()是std::thread::join()的替
- future::wait() 是否与 async() 执行线程的完成同步?
- std::future::wait 是内存障碍吗?(我无法解释这种数据竞赛)
- 在 UWP 应用程序中,future.wait() 在尝试同步来自异步方法的响应时继续等待
- 为什么 future::wait() 块
- 在 std::future 上多次从多个线程调用 wait() 是否安全
- std::future::wait 应该使用这么多 CPU 吗?是否有性能更高的调用