std::packaged_task<R(Args...)>::make_ready_at_thread_exit
来自 cppreference.com
< cpp | thread | packaged task
void make_ready_at_thread_exit( ArgTypes... args ); |
(自 C++11 起) | |
调用存储的任务,就好像通过 INVOKE<R>(f, args...) 一样,其中 f 是存储的任务。任务的返回值或任何由它抛出的异常都存储在 *this 的共享状态中。
共享状态仅在当前线程退出且所有线程局部存储持续时间对象被销毁后才会变为就绪。
内容 |
[编辑] 参数
args | - | 调用存储的任务时要传递的参数 |
[编辑] 返回值
(无)
[编辑] 异常
在以下错误情况下抛出 std::future_error
- 存储的任务已经被调用。错误类别被设置为
promise_already_satisfied
。 - *this 没有共享状态。错误类别被设置为 no_state.
[编辑] 示例
运行此代码
#include <chrono> #include <functional> #include <future> #include <iostream> #include <memory> #include <thread> #include <utility> struct ProgramState { std::packaged_task<void()> task; std::future<void> future; std::thread worker; }; static void worker(std::shared_ptr<ProgramState> state) { state->task.make_ready_at_thread_exit(); // execute task right away auto status = state->future.wait_for(std::chrono::seconds(0)); if (status == std::future_status::timeout) std::cout << "worker: future is not ready yet\n"; else std::cout << "worker: future is ready\n"; std::cout << "worker: exit\n"; } static std::shared_ptr<ProgramState> create_state() { auto state = std::make_shared<ProgramState>(); state->task = std::packaged_task<void()>{[] { std::cout << "task: executed\n"; }}; state->future = state->task.get_future(); state->worker = std::thread{worker, state}; return state; } int main() { auto state = create_state(); state->worker.join(); std::cout << "main: worker finished\n"; auto status = state->future.wait_for(std::chrono::seconds(0)); if (status == std::future_status::timeout) std::cout << "main: future is not ready yet\n"; else std::cout << "main: future is ready\n"; }
输出
task: executed worker: future is not ready yet worker: exit main: worker finished main: future is ready
[编辑] 另请参阅
执行函数 (公有成员函数) |