Namespaces
Variants

std::execution::counting_scope

From cppreference.com
 
 
Execution control library
Concepts
 
Defined in header <execution>
class counting_scope
{
public:
    struct token;

    static constexpr std::size_t max_associations = /* implementation-defined */;

    counting_scope() noexcept;
    counting_scope(counting_scope&&) = delete;
    ~counting_scope();

    token get_token() noexcept;
    void close() noexcept;
    execution::sender auto join() noexcept;
    void request_stop() noexcept;
};
(since C++26)

counting_scope is an async scope: it keeps track of asynchronous operations that are started without anything waiting for their result, so that a program can wait for all of them to finish, and can ask all of them to stop. It counts its associations: work is associated with the scope through a token obtained from get_token, by passing the token to execution::spawn, execution::spawn_future or execution::associate. An association is released when the work no longer needs it: when the operation started by spawn completes, or when the sender or operation state that holds the association is destroyed. The sender returned by join completes when the count is zero.

A program uses a counting_scope where it would otherwise start detached work: for work started from code that is not itself asynchronous, or a number of operations that is not known in advance, such as one operation for each incoming request. Before the scope is destroyed, the program waits for the sender returned by join, typically with std::this_thread::sync_wait, so that the operations do not outlive the objects they use.

counting_scope differs from simple_counting_scope only in its support for cancellation: its tokens give every associated operation a stop token on which stop is requested when request_stop is called, in addition to the stop token of the receiver of that operation.

Lifecycle

A counting_scope is open when it is created: new work can be associated with it. It becomes closed when close is called, or when an operation started from join completes. A closed scope does not accept new associations:

  • spawn destroys the sender without starting it;
  • the senders returned by associate and spawn_future complete with execution::set_stopped.

Once closed, a scope cannot be opened again. While an operation started from join is waiting, the scope remains open unless close is called, so associated work can still associate more work with it.

The destructor calls std::terminate unless the scope was never used, or all operations started from join have completed: a scope with which work was associated must be joined before it is destroyed, even if all of that work has already completed.

Member types

Type Definition
token the scope_token type of the scope, see below

Member constants

Name Value
constexpr std::size_t max_associations(static) the maximum number of associations that the scope can have at the same time; an attempt to associate more work fails as if the scope were closed

Member functions

counting_scope::counting_scope

counting_scope() noexcept;
(since C++26)

Creates an open scope with no associations. counting_scope cannot be copied or moved.

counting_scope::~counting_scope

~counting_scope();
(since C++26)

Destroys the scope. Calls std::terminate if work was associated with the scope and no operation started from join has completed.

counting_scope::get_token

token get_token() noexcept;
(since C++26)

Returns a token that refers to *this. Tokens are cheap to copy, and can be obtained and used from any thread.

counting_scope::close

void close() noexcept;
(since C++26)

Closes the scope: later attempts to associate work with it fail. Work that is already associated is not affected. Calling close on a closed scope has no effect.

counting_scope::join

execution::sender auto join() noexcept;
(since C++26)

Returns a sender that completes when the scope has no associations. When the sender is started, it completes at once if the scope has no associations. Otherwise, it waits until the last association is released, and then completes on the scheduler obtained with execution::get_start_scheduler from the environment of its receiver. When the sender completes, the scope is closed.

The sender completes with execution::set_value(), or with the error and stopped completions of execution::schedule on that scheduler. Its receiver must provide a start scheduler, as sync_wait does.

Calling join does not change the scope: only starting the returned sender does. Starting the returned sender does not close the scope, and it does not request stop for the associated operations.

counting_scope::request_stop

void request_stop() noexcept;
(since C++26)

Requests stop for all operations that were associated with the scope through wrap on its tokens. Stop remains requested: work that is associated with the scope later sees stop requested from the start. request_stop does not close the scope, and does not wait for the operations to complete.

Nested classes

counting_scope::token

struct token
{
    template< execution::sender Sender >
    execution::sender auto wrap( Sender&& snd ) const noexcept(/* see below */);

    /* association */ try_associate() const noexcept;
};
(since C++26)

The token type of counting_scope, which models scope_token. A token refers to its scope, and is not usable after the scope is destroyed.

wrap(snd) returns a sender that behaves like snd, except that the operation receives a stop request either when the stop token of its receiver does or when request_stop is called on the scope. The completion signatures are those of snd. It is noexcept if snd can be moved or copied into the result without throwing an exception.

try_associate() associates work with the scope, and returns an object that owns the association (see scope_association), or an object that owns no association if the scope is closed or already has max_associations associations.

spawn, spawn_future and associate call both: a program uses these member functions directly only when it implements its own such algorithm.

Notes

  • The association is acquired when spawn, spawn_future or associate is called, not when the work is started. The sender returned by associate, and then its operation state, hold the association until they are destroyed, so such a sender or operation state that is kept alive prevents join from completing. Copying such a sender associates the copy with the scope again, and the copy completes with set_stopped if that fails.
  • get_token, close, join, request_stop and the member functions of the tokens can be called from different threads at the same time.
  • An exception thrown between associating work and joining the scope can lead to a call to std::terminate from the destructor, so a program that can throw there has to make sure that the scope is joined, for example in a catch block.
  • Work that has not started running when stop is requested may complete with set_stopped without running at all, for example work that waits in the queue of a scheduler.
  • simple_counting_scope does not change the senders it associates, which makes it cheaper than counting_scope when cancellation is not needed.
  • Before P3149R11, associate was called nest and scope_token was called async_scope_token. Before P3815R1, try_associate returned bool, and tokens had a member function disassociate that released an association. Both changes were made before C++26 was published. Older implementations and articles may show the earlier interface.

Example

Two jobs are spawned into a scope, and run on the parallel scheduler until stop is requested for them. request_stop stops both, and join waits for them. A joined scope accepts no new work. On a system where the parallel scheduler has a single thread, the second job does not start before stop is requested, and completes without running.
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 <chrono>
#include <exception>
#include <execution>
#include <print>
#include <stop_token>
#include <thread>

namespace ex = std::execution;
using namespace std::chrono_literals;

// A job that runs on the parallel scheduler until stop is requested for it
auto job(int id)
{
    return ex::starts_on(ex::get_parallel_scheduler(),
               ex::read_env(std::get_stop_token)
               | ex::then([id](auto token) noexcept
                 {
                     while (!token.stop_requested())
                         std::this_thread::sleep_for(1ms);
                     std::println("Job {} stopped", id);
                 }))
           // spawn accepts only work that cannot fail
           | ex::upon_error([](std::exception_ptr) noexcept {});
}

int main()
{
    ex::counting_scope scope;

    for (int id = 1; id <= 2; ++id)
        ex::spawn(job(id), scope.get_token());

    std::this_thread::sleep_for(10ms);
    scope.request_stop(); // requests stop for every job in the scope
    std::this_thread::sync_wait(scope.join());
    std::println("Joined");

    // A joined scope accepts no new work: associate completes with set_stopped
    auto result = std::this_thread::sync_wait(
        ex::associate(ex::just(42), scope.get_token()));
    std::println("After join: {}", result ? "ran" : "stopped");
}

Possible output:

Job 2 stopped
Job 1 stopped
Joined
After join: stopped

See also

a lightweight, reference-counted asynchronous scope. It tracks how many dynamically spawned asynchronous operations are currently running
(class) [edit]
eagerly launches the given sender within an asynchronous scope, returning immediately without waiting for it to finish
(customization point object)[edit]
eagerly starts a sender within an asynchronous scope and returns a sender that completes with its result, or stopped if the scope did not accept it
(customization point object)[edit]
tries to associate a sender with an asynchronous scope such that the scope can track the lifetime of any asynchronous operations created with the sender
(customization point object)[edit]
specifies a non-owning handle to an asynchronous scope that behaves like a reference to asynchronous scope
(concept) [edit]