Namespaces
Variants

std::promise<R>:: set_value_at_thread_exit

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_value_at_thread_exit ( const R & value ) ;
(1) (C++11 起)
void set_value_at_thread_exit ( R && value ) ;
(2) (C++11 起)
std:: promise < R & > 特化
void set_value_at_thread_exit ( R & value ) ;
(3) (C++11 起)
std:: promise < void > 特化
void set_value_at_thread_exit ( ) ;
(4) (C++11 起)

在不立即就绪状态的情况下将 value 存储到共享状态中。当当前线程退出时,在所有具有线程局部存储期的变量都被销毁之后,该状态才会变为就绪状态。

该操作的行为表现为:在更新 promise 对象时, set_value set_exception set_value_at_thread_exit set_exception_at_thread_exit 会获取与 promise 对象关联的单一互斥锁。

调用此函数不会与对 get_future 的调用产生数据竞争(因此它们无需彼此同步)。

目录

参数

value - 要存储到共享状态中的值

返回值

(无)

异常

std::future_error 在以下情况下发生:

此外:

1) 由被选中复制类型 R 对象的构造函数所抛出的任何异常。
2) 由选择用于移动类型 R 对象的构造函数抛出的任何异常。

示例

#include <future>
#include <iostream>
#include <thread>
int main()
{
    using namespace std::chrono_literals;
    std::promise<int> p;
    std::future<int> f = p.get_future();
    std::thread([&p]
    {
        std::this_thread::sleep_for(1s);
        p.set_value_at_thread_exit(9);
    }).detach();
    std::cout << "Waiting... " << std::flush;
    f.wait();
    std::cout << "Done!\nResult is: " << f.get() << '\n';
}

输出:

Waiting... Done!
Result is: 9

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 2098 C++11 未明确要求抛出哪些异常 已明确说明

参阅

将结果设置为特定值
(公开成员函数)
将结果设置为指示异常,仅在线程退出时传递通知
(公开成员函数)