Namespaces
Variants

std::execution::simple_counting_scope

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

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

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

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

simple_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. 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 simple_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.

The tokens of a simple_counting_scope associate senders with the scope without changing them. counting_scope works the same way, but its tokens also make the work stoppable, so that it can request stop for all the work associated with it.

Lifecycle

A simple_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 Description
token the scope_token type of the scope, see below

Member constants

Constant Description
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

simple_counting_scope::simple_counting_scope

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

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

simple_counting_scope::~simple_counting_scope

~simple_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.

simple_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.

simple_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.

simple_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.

Nested classes

simple_counting_scope::token

struct token
{
    template< execution::sender Sender >
    Sender&& wrap( Sender&& snd ) const noexcept;

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

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

wrap(snd) returns std::forward<Sender>(snd): the scope does not change the senders associated with it.

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 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.
  • The scope gives the work associated with it no stop token, and joining it does not stop the work. Work started with spawn or spawn_future receives a stop token only if the program provides one in the environment passed to them, for example execution::prop(std::get_stop_token, source.get_token()). counting_scope provides one for all its work.
  • 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

A sum is computed on the parallel scheduler by work that splits a large range in two halves and spawns new work for each of them. join waits until all the work, including the work that was spawned while it was waiting, has finished.
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 <exception>
#include <execution>
#include <print>
#include <utility>

namespace ex = std::execution;

ex::simple_counting_scope scope;
std::atomic<long long> total{0};
std::atomic<int> tasks{0};

// Adds up the numbers in [begin, end) on the parallel scheduler. A large
// range is split in two halves, which are spawned into the scope as new work
void add_up(long long begin, long long end)
{
    auto work = ex::schedule(ex::get_parallel_scheduler())
              | ex::then([=] noexcept
                {
                    ++tasks;
                    if (end - begin <= 1000)
                    {
                        long long sum = 0;
                        for (long long i = begin; i != end; ++i)
                            sum += i;
                        total += sum;
                    }
                    else
                    {
                        long long mid = begin + (end - begin) / 2;
                        add_up(begin, mid);
                        add_up(mid, end);
                    }
                })
              // spawn accepts only work that cannot fail
              | ex::upon_error([](std::exception_ptr) noexcept {});
    ex::spawn(std::move(work), scope.get_token());
}

int main()
{
    add_up(1, 1'000'001);
    // join also waits for the work that is spawned while it is waiting
    std::this_thread::sync_wait(scope.join());
    std::println("Sum: {} from {} tasks", total.load(), tasks.load());
}

Output:

Sum: 500000500000 from 2047 tasks

See also

a reference-counted asynchronous scope like simple_counting_scope, which can also request stop for all the asynchronous operations it tracks
(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]