为什么 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;
}
根据 this link,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;
}
请注意,如果您不明确加入 thread
,您仍然会遇到相同的竞争条件(因为 main
可能比 [=15] 更快地完成工作=] 可以自行清理。
工作示例演示:here。
或者您可以分离线程并使用 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;
}
#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;
}
根据 this link,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;
}
请注意,如果您不明确加入 thread
,您仍然会遇到相同的竞争条件(因为 main
可能比 [=15] 更快地完成工作=] 可以自行清理。
工作示例演示:here。
或者您可以分离线程并使用 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;
}