void set_exception( std::exception_ptr p );
|
(C++11 起) | |
存储异常指针 p
到共享状态中,并令状态就绪。
set_value 、 set_exception 、 set_value_at_thread_exit 和 set_exception_at_thread_exit
的操作表现类似。在更新 promise 对象时获得单个与 promise 对象关联的互斥。
若无共享状态,或共享状态已存储值或异常,则抛出异常。
目录 |
p | - | 要存储的异常指针。若 p 为空则行为未定义。
|
(无)
遇到下列条件时为 std::future_error :
#include <thread> #include <iostream> #include <future> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p]{ try { // 可能抛出的代码 throw std::runtime_error("Example"); } catch(...) { try { // 存储任何抛出的异常于 promise p.set_exception(std::current_exception()); } catch(...) {} // set_exception() 亦可能抛出 } }); try { std::cout << f.get(); } catch(const std::exception& e) { std::cout << "Exception from the thread: " << e.what() << '\n'; } t.join(); }
输出:
Exception from the thread: Example
设置结果为指示异常,同时仅在线程退出时分发提醒 (公开成员函数) |