Namespaces
Variants

std::execution::task_scheduler

From cppreference.com
 
 
Execution control library
Concepts
 
Defined in header <execution>
class task_scheduler
{
public:
    using scheduler_concept = scheduler_tag;

    template< class Sch, class Allocator = std::allocator<void> >
        requires (!std::same_as<task_scheduler, std::remove_cvref_t<Sch>>) &&
                 scheduler<Sch>
    explicit task_scheduler( Sch&& sch, Allocator alloc = {} );

    task_scheduler( const task_scheduler& ) = default;
    task_scheduler& operator=( const task_scheduler& ) = default;

    /* unspecified */ schedule();

    friend bool operator==( const task_scheduler& lhs,
                            const task_scheduler& rhs ) noexcept;
    template< class Sch >
        requires (!std::same_as<task_scheduler, Sch>) && scheduler<Sch>
    friend bool operator==( const task_scheduler& lhs, const Sch& rhs ) noexcept;
};
(since C++26)

task_scheduler is a type-erased scheduler: it holds a scheduler of any type whose scheduling cannot fail, and forwards scheduling to it.

It exists for task. A task resumes on the scheduler it was started on after every co_await, so it has to store that scheduler. The type of a task is fixed by the declaration of the coroutine, but the scheduler is known only when the task is connected to a receiver. By default, a task therefore stores its start scheduler as a task_scheduler, so that the same task can be started on any scheduler that can be wrapped. A task whose environment type names a specific start_scheduler_type avoids the cost of type erasure, but can then only be started on schedulers that can be converted to that type.

task_scheduler can also be used outside of tasks, wherever the type of a scheduler should not be part of an interface. It is not a general-purpose wrapper for every scheduler: it only provides scheduling, the bulk algorithms, and the forward progress guarantee of the wrapped scheduler, and other queries of the wrapped scheduler are not available through it.

Wrapping a scheduler

  • The constructor stores a copy of sch, or moves it if it is an rvalue. The memory for it is allocated with alloc, and any other memory that the task_scheduler allocates later also comes from a copy of alloc. Implementations are encouraged to store small schedulers without allocating memory.
  • If the sender returned by execution::schedule(sch) can complete in any way other than set_value() when stop cannot be requested, the program is ill-formed. The schedulers of run_loop and inline_scheduler meet this requirement. parallel_scheduler does not, because its scheduling can fail with an std::exception_ptr, so it cannot be wrapped.
  • There is no default constructor, and no move constructor: moving a task_scheduler copies it. A task_scheduler therefore always holds a scheduler, even after it has been moved from.

Scheduling

  • execution::schedule(ts) returns a sender that, when started, schedules on the wrapped scheduler. It completes with set_value() on the wrapped scheduler's execution resource, or with set_stopped() if the sender of the wrapped scheduler does. It never completes with an error, and if the stop token of the receiver cannot request stop, it can only complete with set_value().
  • The value completion scheduler of that sender is the task_scheduler itself, not the scheduler it wraps.
  • execution::get_forward_progress_guarantee(ts) returns the forward progress guarantee of the wrapped scheduler.
  • The bulk algorithms, bulk, bulk_chunked, and bulk_unchunked, are passed on to the wrapped scheduler when they run on a task_scheduler, as in execution::schedule(ts) | execution::bulk(policy, n, f). A scheduler with its own implementation of the bulk algorithms, such as one that runs the iterations in parallel, keeps using it through the wrapper.

Comparison

Two task_scheduler objects compare equal if the schedulers they wrap have the same type and compare equal. A task_scheduler can also be compared with a scheduler of another type: ts == sch is true if ts wraps a scheduler of the type of sch that compares equal to sch.

Notes

  • Type erasure has a cost. Every schedule goes through an indirect call, and constructing a task_scheduler can allocate memory. When the type of the scheduler is known and performance matters, a template parameter avoids both.
  • Since the start scheduler of a task is a task_scheduler by default, a task cannot be started directly on a scheduler that cannot be wrapped: execution::starts_on(execution::get_parallel_scheduler(), t) is ill-formed for such a task. The task can still run work on that scheduler with co_await execution::starts_on(execution::get_parallel_scheduler(), work), and then resumes on its own scheduler. Alternatively, a different start_scheduler_type can be given in the task's environment type.
  • In earlier drafts, the sender returned by schedule could complete with an std::error_code or an std::exception_ptr, and any scheduler could be wrapped. The requirement that the wrapped scheduler cannot fail was added before C++26 was published, together with the same requirement on affine, so that a task can always return to its scheduler.
  • The standard describes task_scheduler in terms of parallel_scheduler_replacement::parallel_scheduler_backend, the abstract base class that a program derives from to replace the thread pool of parallel_scheduler. The wrapped scheduler is held in an object of a class derived from it, and its virtual functions are how both schedule and the bulk algorithms reach the wrapped scheduler. In stdexec, the operation state of the sender returned by schedule contains a fixed-size buffer in which the operation state of the wrapped scheduler's sender is constructed, so scheduling allocates no memory. A scheduler whose operation state does not fit is rejected at compile time.

Example

thread_of is not a template, and runs work on a run_loop and on an inline_scheduler through task_scheduler. A task started on the run_loop reads its start scheduler, which is a task_scheduler that wraps the scheduler of the loop.
The execution control library components may not be available in the online compilers yet, so this link runs the example on Compiler Explorer with stdexec (one of the reference implementations).

#include <concepts>
#include <execution>
#include <print>
#include <thread>

namespace ex = std::execution;

// Not a template: accepts any scheduler whose scheduling cannot fail
std::thread::id thread_of(ex::task_scheduler sch)
{
    auto sndr = ex::schedule(sch) | ex::then([]
    {
        return std::this_thread::get_id();
    });
    auto [id] = std::this_thread::sync_wait(std::move(sndr)).value();
    return id;
}

// By default, a task keeps the scheduler it was started on in a
// task_scheduler
ex::task<bool> started_on(ex::task_scheduler expected)
{
    auto sch = co_await ex::read_env(ex::get_start_scheduler);
    static_assert(std::same_as<decltype(sch), ex::task_scheduler>);
    co_return sch == expected;
}

int main()
{
    ex::run_loop loop;
    std::jthread worker([&loop] { loop.run(); });

    ex::task_scheduler on_loop(loop.get_scheduler());
    ex::task_scheduler here(ex::inline_scheduler{});
    std::println("Work runs on the loop's thread: {}",
                 thread_of(on_loop) == worker.get_id());
    std::println("Inline work runs on this thread: {}",
                 thread_of(here) == std::this_thread::get_id());

    std::println("Wrappers of the same scheduler are equal: {}",
                 on_loop == ex::task_scheduler(loop.get_scheduler()));
    std::println("Wrappers of different schedulers are equal: {}",
                 on_loop == here);

    auto work = ex::starts_on(loop.get_scheduler(), started_on(on_loop));
    auto [same] = std::this_thread::sync_wait(std::move(work)).value();
    std::println("The task was started on the loop: {}", same);
    loop.finish();
}

Output:

Work runs on the loop's thread: true
Inline work runs on this thread: true
Wrappers of the same scheduler are equal: true
Wrappers of different schedulers are equal: false
The task was started on the loop: true

See also

specifies that a type is a scheduler, a handle to an execution resource
(concept) [edit]
represents a sender that can be used as the return type of coroutine functions
(class template) [edit]
a trivial scheduler that completes immediately and synchronously on the thread that calls std::execution::start on the operation state produced by its sender
(class) [edit]
represents a handle of a shared global execution resource (such as a OS-provided system thread pool) optimized for parallel execution
(class) [edit]
execution resource holding a thread-safe MPSC task queue and a manually-driven event loop
(class) [edit]
adapts a sender into one that completes on the scheduler the operation was started on
(customization point object)[edit]
asks a queryable object for the scheduler an operation will be or was started on
(customization point object)[edit]