Namespaces
Variants

std::promise<R>:: set_exception

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
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

示例

#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

参见

在线程退出时设置结果为异常状态并仅在线程退出时交付通知
(公开成员函数)