std::promise<R>:: set_exception
From cppreference.net
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::promise
| Member functions | ||||
| Getting the result | ||||
| Setting the result | ||||
|
promise::set_exception
|
||||
| Non-member Functions | ||||
| Helper Classes | ||||
|
void
set_exception
(
std::
exception_ptr
p
)
;
|
(C++11 起) | |
原子地将异常指针 p 存储到共享状态中,并使该状态进入就绪状态。
该操作的行为表现为:在更新 promise 对象时,
set_value
、
set_exception
、
set_value_at_thread_exit
和
set_exception_at_thread_exit
会获取与 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 { // 可能抛出异常的代码 throw std::runtime_error("Example"); } catch (...) { try { // 将抛出的任何内容存储到 promise 中 p.set_exception(std::current_exception()); // 或者改为抛出自定义异常 // p.set_exception(std::make_exception_ptr(MyException("mine"))); } catch (...) {} // set_exception() 也可能抛出异常 } }); try { std::cout << f.get(); } catch (const std::exception& e) { std::cout << "来自线程的异常: " << e.what() << '\n'; } t.join(); }
输出:
Exception from the thread: Example
参见
|
在线程退出时设置结果为异常状态并仅在线程退出时交付通知
(公开成员函数) |