命名空间
变体
操作

std::execution::scheduler

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

concept scheduler =
    std::derived_from<
        typename std::remove_cvref_t<Sch>::scheduler_concept,
        scheduler_t> &&
    /*queryable*/<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++ 执行库协同工作的轻量级执行资源(如线程池)的处理程序。

[编辑] 语义要求

给定类型为 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 来等待已提交函数对象的完成)

[编辑] 示例

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

[编辑] 另请参阅

准备一个任务图,以便在给定的调度器上执行
(自定义点对象)[编辑]