std::promise<R>::set_exception
来自 cppreference.cn
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 对象关联的单个互斥锁。
如果不存在共享状态或共享状态已存储值或异常,则抛出异常。
对此函数的调用不会引入与 get_future 的调用的数据竞争(因此它们不需要彼此同步)。
目录 |
[编辑] 参数
p | - | 要存储的异常指针。如果 p 为空,则行为未定义 |
[编辑] 返回值
(无)
[编辑] 异常
std::future_error 在以下条件下抛出
- *this 没有共享状态。错误代码设置为 no_state。
- 共享状态已存储值或异常。错误代码设置为 promise_already_satisfied。
[编辑] 示例
运行此代码
#include <future> #include <iostream> #include <thread> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p] { try { // code that may throw throw std::runtime_error("Example"); } catch (...) { try { // store anything thrown in the promise p.set_exception(std::current_exception()); // or throw a custom exception instead // p.set_exception(std::make_exception_ptr(MyException("mine"))); } catch (...) {} // set_exception() may throw too } }); 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
[编辑] 参见
设置结果以指示异常,同时仅在线程退出时传递通知 (公共成员函数) |