std::packaged_task<R(Args...)>:: make_ready_at_thread_exit
From cppreference.net
<
cpp
|
thread
|
packaged task
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::packaged_task
| Member functions | ||||
| Getting the result | ||||
| Execution | ||||
|
packaged_task::make_ready_at_thread_exit
|
||||
| Non-member functions | ||||
| Helper classes | ||||
|
(until C++17)
|
||||
| Deduction guides (C++17) |
|
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(); // 立即执行任务 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
参见
|
执行函数
(公开成员函数) |