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
[編輯] 參閱
執行函式 (公共成員函式) |