std::execution::parallel_scheduler
| Defined in header <execution>
|
||
class parallel_scheduler { /* unspecified */ };
|
(since C++26) | |
parallel_scheduler is a scheduler for a shared execution resource that runs work in parallel, such as a thread pool of the operating system. It is obtained by calling get_parallel_scheduler; the standard specifies no other way to create one. Like every scheduler, it can be copied and compared, and the copies are handles to the same execution resource.
When the different parts of a program create thread pools of their own, the program can end up with more threads than the processors can run, and the parts cannot share the processors efficiently. parallel_scheduler is meant to be the one execution resource that all parts of a program, including libraries that do not know about each other, use for work that needs processor time. The standard library provides the execution resource, and a program can replace it with its own, for example to share the thread pool of another parallel runtime.
Scheduling
execution::schedule(sch)returns a sender that, when started, hands the work over to the execution resource. It completes withset_value()on one of the execution agents of the resource.- It can complete with
set_stopped()if stop is requested on the stop token of the receiver before the work runs. Whether, and how soon, the execution resource reacts to stop requests is unspecified. - It can complete with
set_errorand an std::exception_ptr if the execution resource cannot run the work. Because scheduling can fail, aparallel_schedulercannot be wrapped in a task_scheduler or used with affine, so a task cannot be started directly on it. A task can still run work on it withco_await execution::starts_on(execution::get_parallel_scheduler(), work). execution::get_forward_progress_guarantee(sch)returnsexecution::forward_progress_guarantee::parallel: work that has started running on an execution agent of the resource keeps making progress, but work that has not started yet is not guaranteed to start while other work is running.
Bulk algorithms
parallel_scheduler provides its own implementation of bulk_chunked and bulk_unchunked. It is used when the sender before the algorithm completes on a parallel_scheduler, as in execution::schedule(sch) | execution::bulk_chunked(policy, n, f), or after execution::continues_on(sndr, sch). A bulk sender is replaced with a bulk_chunked sender when it is connected (see default_domain), so it uses the same implementation.
The execution policy decides whether the iterations run in parallel:
- With execution::par or execution::par_unseq, the iterations are spread over the execution agents of the resource.
bulk_chunkedcallsf(begin, end, args...)for subranges that together cover[0, n)exactly once, andbulk_unchunkedcallsf(i, args...)separately for each index. The execution resource chooses the number and the size of the chunks, and the calls can run at the same time on different threads. - With execution::seq or execution::unseq, all iterations run on one execution agent of the resource.
bulk_chunkedcallsf(0, n, args...)once, andbulk_unchunkedcallsf(i, args...)for each index in a loop, in order. - For an implementation-defined execution policy, it is implementation-defined which of the two happens.
In both cases, args are lvalues that refer to the values sent by the previous sender, and every call of f gets the same objects.
Replacing the execution resource
The execution resource is reached through an object of a class derived from parallel_scheduler_replacement::parallel_scheduler_backend, whose virtual member functions schedule work, and run chunked and unchunked bulk work. get_parallel_scheduler obtains this object by calling parallel_scheduler_replacement::query_parallel_scheduler_backend, which is a replaceable function, like operator new. A program that defines its own version of this function, returning an std::shared_ptr to its own backend object, makes every parallel_scheduler in the program use that backend. If the function returns a null pointer, get_parallel_scheduler calls std::terminate.
Two parallel_scheduler objects compare equal if and only if they use the same backend object.
Notes
- Work that runs on a
parallel_schedulershould not block while it waits for other work that needs the same execution resource. Examples are an iteration ofbulkthat waits on a std::latch or std::barrier for the other iterations, and work that calls this_thread::sync_wait on a sender that also runs on the resource. The resource can have fewer threads than there is blocked work, and then the work that would unblock it might never start, so the program can deadlock. Blocking I/O also holds a thread that other work could use. - The name refers to the forward progress guarantee. The standard does not require the execution resource to have more than one thread.
- The implementation of the bulk algorithms is chosen when the sender is connected, from the scheduler on which the previous sender completes. A bulk algorithm that does not follow a completion on a
parallel_scheduler, as inthis_thread::sync_wait(execution::just() | execution::bulk(execution::par, n, f)), uses the default implementation, which runs all iterations one after another on the thread on which the previous sender completes, whatever the execution policy. - Typical implementations (stdexec, beman.execution) use the thread pool of the operating system where there is one, and a thread pool of their own otherwise. stdexec uses libdispatch on Apple platforms, the Windows thread pool on Windows, and otherwise a thread pool with one thread for each hardware thread.
parallel_schedulerwas proposed assystem_scheduler, and the namespace of its replacement interface was calledsystem_context_replaceabilityuntil it was renamed toparallel_scheduler_replacementby P4154R0. In earlier drafts, the bulk algorithms ran the iterations in parallel whatever the execution policy; P3804R2 made them depend on it. Both changes were made before C++26 was published, and older implementations and articles may show the earlier interface.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_parallel_scheduler |
202506L |
(C++26) | std::execution::parallel_scheduler
|
Example
The same work is done on the parallel scheduler with two execution policies. With par, bulk_chunked divides it into chunks that run on several threads; with seq, it runs in one call. The number of chunks depends on the execution resource.
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 <atomic>
#include <cstddef>
#include <execution>
#include <numeric>
#include <print>
#include <thread>
#include <vector>
namespace ex = std::execution;
// Fills a vector with squares on the parallel scheduler and adds them up,
// counting the chunks that bulk_chunked divides the work into
void sum_of_squares(const auto& policy, const char* name)
{
std::vector<long> squares(1000);
std::atomic<int> chunks = 0;
auto work = ex::schedule(ex::get_parallel_scheduler())
| ex::bulk_chunked(policy, squares.size(),
[&](std::size_t begin, std::size_t end)
{
++chunks;
for (std::size_t i = begin; i != end; ++i)
squares[i] = long(i * i);
})
| ex::then([&]
{
return std::reduce(squares.begin(), squares.end());
});
auto [sum] = std::this_thread::sync_wait(std::move(work)).value();
std::println("{}: the sum is {}, computed in {} chunk(s)",
name, sum, chunks.load());
}
int main()
{
auto sch = ex::get_parallel_scheduler();
// Every call returns a handle to the same shared execution resource
std::println("Same execution resource: {}",
sch == ex::get_parallel_scheduler());
std::println("Parallel forward progress: {}",
ex::get_forward_progress_guarantee(sch)
== ex::forward_progress_guarantee::parallel);
// With par, the iterations are spread over the threads of the resource;
// with seq, they all run in one call, on one thread
sum_of_squares(ex::par, "par");
sum_of_squares(ex::seq, "seq");
}
Possible output:
Same execution resource: true
Parallel forward progress: true
par: the sum is 332833500, computed in 4 chunk(s)
seq: the sum is 332833500, computed in 1 chunk(s)
See also
obtains a parallel_scheduler for the shared execution resource that runs work in parallel (function) | |
serves as the abstraction bridge between the user-facing parallel_scheduler and the backend execution resource (such as a OS-provided system thread pool) (class) | |
returns the backend object that every parallel_scheduler uses; a program can replace it to provide its own backend (function) | |
(C++26)(C++26)(C++26) |
runs a function for every index in a range after a sender completes, so the work can be spread over a scheduler's execution resources (customization point object) |
| specifies a forward progress guarantee of execution agents created by the scheduler's associated execution resource (enum) | |
(C++26) |
execution resource holding a thread-safe MPSC task queue and a manually-driven event loop (class) |
(C++26) |
provides a uniform, type-erased interface, which allows to store, pass around, and invoke scheduling operations on arbitrary infallible schedulers (class) |