std::execution::scheduler
出自cppreference.com
| 在標頭 <execution> 定義
|
||
| |
(1) | (C++26 起) |
| 輔助標籤類型 |
||
| |
(2) | (C++26 起) |
scheduler 概念由調度器 類型實現,它們是執行資源的輕量句柄,比如與 C++ 執行庫協作的線程池。
語義要求
給定一個 Sch 類型的調度器和 Env 類型的執行環境,並滿足 sender_in<schedule_result_t<Sch>, Env>,則 /*sender-in-of*/<schedule_result_t<Sch>, Env> 得以實現。
調度器的複製構造函數、析構函數、相等性比較或者 swap 成員函數都必須不拋出異常。
所有這些成員函數,以及該調度器類型的 schedule 函數都必須是線程安全的。
僅當兩個調度器表示同一個執行資源時,它們相等。
對於給定調度器 sch,表達式 get_completion_scheduler<set_value_t>(get_env(schedule(sch))) 與 sch 比較為相等。
對於給定調度器 sch,如果表達式 get_domain(sch) 良構,那麼表達式 get_domain(get_env(schedule(sch))) 也良構且具有相同類型。
調度器的析構函數,不能阻塞於任何與 schedule 返回的發送器對象向連接的接收器的完成(底層資源可以提供單獨 API 用以等待已提交函數對象的完成)。
示例
這是對 std::execution::run_loop 的簡單包裝,它在一個專門線程中持續拉取 run_loop 的隊列。演示代碼使用草案的參考實現:https://godbolt.org/z/146fY4Y91
運行此代碼
#include <execution>
#include <iostream>
#include <thread>
class single_thread_context
{
std::execution::run_loop loop_{};
std::jthread thread_;
public:
single_thread_context()
: thread_([this] { loop_.run(); })
{}
single_thread_context(single_thread_context&&) = delete;
~single_thread_context()
{
loop_.finish();
}
std::execution::scheduler auto get_scheduler() noexcept
{
return loop_.get_scheduler();
}
};
int main()
{
single_thread_context ctx;
std::execution::sender auto snd =
std::execution::schedule(ctx.get_scheduler())
| std::execution::then([]
{
std::cout << "Hello world! Have an int.\n";
return 015;
})
| std::execution::then([](int arg) { return arg + 42; });
auto [i] = std::this_thread::sync_wait(snd).value();
std::cout << "回到主线程,结果为 " << i << '\n';
}
輸出:
Hello world! Have an int.
回到主线程,结果为 55
參閱
(C++26) |
準備一個要在給定調度器上執行的任務圖 (定製點對象) |