命名空间
变体
操作

std::execution::scheduler

来自 cppreference.cn
< cpp‎ | execution
 
 
 
在头文件 <execution> 中定义
template< class Sch >

概念 scheduler =
    std::derived_from<
        typename std::remove_cvref_t<Sch>::scheduler_concept,
        scheduler_t> &&
    /*可查询的*/<Sch> &&
    requires(Sch&& sch)
    {
        {
            std::execution::schedule(std::forward<Sch>(sch))
        } -> std::execution::sender;
        {
            auto(
                std::execution::get_completion_scheduler<
                    std::execution::set_value_t>(
                        std::execution::get_env(
                            std::execution::schedule(
                                std::forward<Sch>(sch)))))
        } -> std::same_as<std::remove_cvref_t<Sch>>;
    } &&
    std::equality_comparable<std::remove_cvref_t<Sch>> &&
    std::copy_constructible<std::remove_cvref_t<Sch>>;

};
(1) (自 C++26)
辅助标签类型
struct scheduler_t {};
(2) (自 C++26)

概念 scheduler调度器类型建模,即与 C++ 执行库一起工作的执行资源(如线程池)的轻量级处理程序。

[edit] 语义要求

给定类型为 Sch 的调度器和类型为 Env 的执行环境,使得 sender_in<schedule_result_t<Sch>, Env> 得到满足,则 /*sender-in-of*/<schedule_result_t<Sch>, Env> 被建模。

调度器的复制构造函数、析构函数、相等比较或交换成员函数必须是非抛出的。

所有这些成员函数以及调度器类型的 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 来等待提交的函数对象的完成)

[edit] 示例

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 << "Back in the main thread, result is " << i << '\n';
}

输出

Hello world! Have an int.
Back in the main thread, result is 55

[edit] 参见

准备任务图以在给定的调度器上执行
(定制点对象)[编辑]