userver: Concurrency
Loading...
Searching...
No Matches
Concurrency

Detailed Description

Files

file  userver/utils/atomic.hpp
 Helper algorithms to work with atomics.

Classes

class  engine::Mutex
 std::mutex replacement for asynchronous tasks. More...
class  utils::AimdLimiter
 Thread safe AIMD (Additive Increase Multiplicative Decrease) limiter. More...
class  utils::TokenBucket
class  concurrent::AsyncEventChannel< Args >
class  concurrent::AsyncEventSource< Args >
 The read-only side of an event channel. Events are delivered to listeners in a strict FIFO order, i.e. only after the event was processed a new event may appear for processing, same listener is never called concurrently. More...
class  concurrent::BackgroundTaskStorageCore
class  concurrent::BackgroundTaskStorage
class  concurrent::ConflatedEventChannel
 A non-blocking version of 'AsyncEventChannel'. More...
class  concurrent::MpscQueue< T >
class  concurrent::MutexSet< Key, Hash, Equal >
 A dynamic set of mutexes. More...
class  concurrent::StripedCounter
 A contention-free sharded atomic counter, with memory consumption and read performance traded for write performance. Intended to be used for write-heavy counters, mostly in metrics. More...
class  concurrent::Variable< Data, Mutex >
class  dist_lock::DistLockStrategyBase
 Interface for distributed lock strategies. More...
class  dist_lock::DistLockedTask
 A task that tries to acquire a distributed lock and runs user callback once while the lock is held. More...
class  drivers::SubscribableFutureWrapper< SubscribableFuture >
 An adaptor for working with certain external futures. More...
class  engine::ConditionVariable
 std::condition_variable replacement for asynchronous tasks More...
class  engine::Promise< T >
 std::promise replacement for asynchronous tasks that works in pair with engine::Future More...
class  engine::Future< T >
 std::future replacement for asynchronous tasks that works in pair with engine::Promise More...
class  engine::MultiConsumerEvent
 A single-producer, multiple-consumers event. More...
class  engine::PulseEvent
 A multiple-producers, multiple-consumers notification. More...
class  engine::CancellableSemaphore
 Class that allows up to max_simultaneous_locks concurrent accesses to the critical section. It honours task cancellation, unlike Semaphore. More...
class  engine::Semaphore
 Class that allows up to max_simultaneous_locks concurrent accesses to the critical section. It ignores task cancellation, unlike CancellableSemaphore. More...
class  engine::SharedMutex
 std::shared_mutex replacement for asynchronous tasks. More...
class  engine::SingleConsumerEvent
 A multiple-producers, single-consumer event. More...
class  engine::SingleUseEvent
 A single-producer, single-consumer event. More...
class  engine::SingleWaitingTaskMutex
 Lighter version of Mutex with not more than 1 waiting task. More...
class  engine::TaskInheritedVariable< T >
 TaskInheritedVariable is a per-coroutine variable of arbitrary type. More...
class  engine::TaskLocalVariable< T >
 TaskLocalVariable is a per-coroutine variable of arbitrary type. More...
class  engine::WaitAnyContext
 Stores a set of awaitables and allows waiting for completion of any of the stored awaitables. More...
class  rcu::Variable< T, RcuTraits >
 Read-Copy-Update variable. More...
class  rcu::RcuMap< Key, Value, RcuMapTraits >
 Map-like structure allowing RCU keyset updates. More...
class  utils::PeriodicTask
 Task that periodically runs a user callback. Callback is started after the previous callback execution is finished every period + A - B, where: More...

Typedefs

template<typename T>
using concurrent::NonFifoMpmcQueue = GenericQueue<T, impl::SimpleQueuePolicy<true, true>>
 Non FIFO multiple producers multiple consumers queue.
template<typename T>
using concurrent::NonFifoMpscQueue = GenericQueue<T, impl::SimpleQueuePolicy<true, false>>
 Non FIFO multiple producers single consumer queue.
template<typename T>
using concurrent::SpmcQueue = GenericQueue<T, impl::SimpleQueuePolicy<false, true>>
 Single producer multiple consumers queue.
template<typename T>
using concurrent::SpscQueue = GenericQueue<T, impl::SimpleQueuePolicy<false, false>>
 Single producer single consumer queue.
template<typename T>
using concurrent::UnboundedNonFifoMpscQueue = GenericQueue<T, impl::NoMaxSizeQueuePolicy<true, false>>
 Like concurrent::NonFifoMpscQueue, but does not support setting max size and is thus slightly faster.
template<typename T>
using concurrent::UnboundedSpmcQueue = GenericQueue<T, impl::NoMaxSizeQueuePolicy<false, true>>
 Like concurrent::SpmcQueue, but does not support setting max size and is thus slightly faster.
template<typename T>
using concurrent::UnboundedSpscQueue = GenericQueue<T, impl::NoMaxSizeQueuePolicy<false, false>>
 Like concurrent::SpscQueue, but does not support setting max size and is thus slightly faster.
using concurrent::StringStreamQueue = GenericQueue<std::string, impl::ContainerQueuePolicy<false, false>>
 Single producer single consumer queue of std::string which is bounded by the total bytes inside the strings.

Enumerations

enum class  engine::WaitAnyError : std::uint8_t {
  engine::WaitAnyError::kEmpty ,
  engine::WaitAnyError::kCancelled ,
  engine::WaitAnyError::kTimeout
}
 The reason why WaitAnyContext::Wait and friends did not return the index of a completed awaitable. More...

Functions

template<typename... Tasks>
void engine::WaitAllChecked (Tasks &... tasks)
 Waits for the successful completion of all of the specified tasks or for the cancellation of the caller.
template<typename Function, typename... Args>
auto utils::Async (std::string name, Function &&f, Args &&... args)
 Starts an asynchronous task.
template<typename Function, typename... Args>
auto utils::Async (engine::TaskProcessor &task_processor, std::string name, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::AsyncHideSpan (Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::AsyncHideSpan (engine::TaskProcessor &task_processor, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::CriticalAsync (engine::TaskProcessor &task_processor, std::string name, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::SharedAsync (engine::TaskProcessor &task_processor, std::string name, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::CriticalAsync (std::string name, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::SharedCriticalAsync (std::string name, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::SharedAsync (std::string name, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::Async (std::string name, engine::Deadline deadline, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::AsyncBackground (std::string name, engine::TaskProcessor &task_processor, Function &&f, Args &&... args)
template<typename Function, typename... Args>
auto utils::CriticalAsyncBackground (std::string name, engine::TaskProcessor &task_processor, Function &&f, Args &&... args)
template<typename T, typename Func>
T utils::AtomicUpdate (std::atomic< T > &atomic, Func updater)
 Atomically performs the operation of updater on atomic.
template<typename T>
T utils::AtomicMin (std::atomic< T > &atomic, T value)
 Concurrently safe sets atomic to a value if value is less.
template<typename T>
T utils::AtomicMax (std::atomic< T > &atomic, T value)
 Concurrently safe sets atomic to a value if value is greater.
template<std::ranges::input_range Range, typename Start>
requires std::invocable<const Start&, std::ranges::range_reference_t<Range>> && impl::CollectableFuture<std::invoke_result_t
<const Start&, std::ranges::range_reference_t<Range>>>
auto concurrent::CollectInParallel (Range &&input_range, ParallelCollectSettings settings, const Start &start) -> std::vector< utils::expected< impl::CollectedValue< std::invoke_result_t< const Start &, std::ranges::range_reference_t< Range > > >, std::exception_ptr > >
 Collect results from lazily started operations with bounded concurrency.
template<typename SubscribableFuture>
void drivers::WaitForSubscribableFuture (SubscribableFuture &&future)
 Waits on the given future as described on drivers::SubscribableFutureWrapper.
template<typename SubscribableFuture>
engine::FutureStatus drivers::TryWaitForSubscribableFuture (SubscribableFuture &&future, engine::Deadline deadline)
template<typename... Tasks>
auto engine::GetAll (Tasks &... tasks)
 Waits for the successful completion of all of the specified tasks or the cancellation of the caller.
template<typename... Tasks>
std::optional< std::size_t > engine::WaitAny (Tasks &... tasks)
 Waits for the completion of any of the specified tasks or the cancellation of the caller.
template<typename... Awaitables>
WaitAnyContext engine::MakeWaitAny (Awaitables &... awaitables)
 Produces a WaitAnyContext for the given awaitables and sequences of awaitables.

Typedef Documentation

◆ NonFifoMpmcQueue

template<typename T>
using concurrent::NonFifoMpmcQueue = GenericQueue<T, impl::SimpleQueuePolicy<true, true>>

Non FIFO multiple producers multiple consumers queue.

Items from the same producer are always delivered in the production order. Items from different producers (or when using a MultiProducer token) are delivered in an unspecified order. In other words, FIFO order is maintained only within producers, but not between them. This may lead to increased peak latency of item processing.

In exchange for this, the queue has lower contention and increased throughput compared to a conventional lock-free queue.

See also
Synchronization Primitives

Definition at line 51 of file queue_fwd.hpp.

◆ NonFifoMpscQueue

template<typename T>
using concurrent::NonFifoMpscQueue = GenericQueue<T, impl::SimpleQueuePolicy<true, false>>

Non FIFO multiple producers single consumer queue.

See also
concurrent::NonFifoMpmcQueue for the description of what NonFifo means.
Synchronization Primitives

Definition at line 60 of file queue_fwd.hpp.

◆ SpmcQueue

template<typename T>
using concurrent::SpmcQueue = GenericQueue<T, impl::SimpleQueuePolicy<false, true>>

Single producer multiple consumers queue.

See also
Synchronization Primitives

Definition at line 68 of file queue_fwd.hpp.

◆ SpscQueue

template<typename T>
using concurrent::SpscQueue = GenericQueue<T, impl::SimpleQueuePolicy<false, false>>

Single producer single consumer queue.

See also
Synchronization Primitives
Examples
samples/tcp_full_duplex_service/main.cpp.

Definition at line 76 of file queue_fwd.hpp.

◆ StringStreamQueue

using concurrent::StringStreamQueue = GenericQueue<std::string, impl::ContainerQueuePolicy<false, false>>

Single producer single consumer queue of std::string which is bounded by the total bytes inside the strings.

See also
Synchronization Primitives

Definition at line 107 of file queue_fwd.hpp.

◆ UnboundedNonFifoMpscQueue

template<typename T>
using concurrent::UnboundedNonFifoMpscQueue = GenericQueue<T, impl::NoMaxSizeQueuePolicy<true, false>>

Like concurrent::NonFifoMpscQueue, but does not support setting max size and is thus slightly faster.

See also
Synchronization Primitives

Definition at line 84 of file queue_fwd.hpp.

◆ UnboundedSpmcQueue

template<typename T>
using concurrent::UnboundedSpmcQueue = GenericQueue<T, impl::NoMaxSizeQueuePolicy<false, true>>

Like concurrent::SpmcQueue, but does not support setting max size and is thus slightly faster.

See also
Synchronization Primitives

Definition at line 92 of file queue_fwd.hpp.

◆ UnboundedSpscQueue

template<typename T>
using concurrent::UnboundedSpscQueue = GenericQueue<T, impl::NoMaxSizeQueuePolicy<false, false>>

Like concurrent::SpscQueue, but does not support setting max size and is thus slightly faster.

See also
Synchronization Primitives

Definition at line 100 of file queue_fwd.hpp.

Enumeration Type Documentation

◆ WaitAnyError

enum class engine::WaitAnyError : std::uint8_t
strong

The reason why WaitAnyContext::Wait and friends did not return the index of a completed awaitable.

Enumerator
kEmpty 

there were no awaitables to wait for

kCancelled 

the wait operation was interrupted by task cancellation

kTimeout 

the wait operation timed out (see also FutureStatus)

Definition at line 120 of file wait_any.hpp.

Function Documentation

◆ Async() [1/3]

template<typename Function, typename... Args>
auto utils::Async ( engine::TaskProcessor & task_processor,
std::string name,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Task execution may be cancelled before the function starts execution in case of TaskProcessor overload.

Parameters
task_processorTask processor to run on
nameName of the task to show in logs
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult

Definition at line 75 of file async.hpp.

◆ Async() [2/3]

template<typename Function, typename... Args>
auto utils::Async ( std::string name,
engine::Deadline deadline,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Task execution may be cancelled before the function starts execution in case of TaskProcessor overload.

Parameters
nameName of the task to show in logs
deadlineDeadline to set for the child task, upon reaching it the task will be cancelled
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult

Definition at line 263 of file async.hpp.

◆ Async() [3/3]

template<typename Function, typename... Args>
auto utils::Async ( std::string name,
Function && f,
Args &&... args )
nodiscard

Starts an asynchronous task.

By default, arguments are copied or moved inside the resulting TaskWithResult, like std::thread does. To pass an argument by reference, wrap it in std::ref / std::cref or capture the arguments using a lambda.

For more documentation on launching asynchronous tasks:

See also
intro_tasks

About this specific overload

This is the overload that should be used by default.

  • The task will be launched on the current TaskProcessor.
  • Only 1 task may call Wait or Get on this task.
  • The task may be cancelled before the function starts execution in case of TaskProcessor overload. Also, if the task is cancelled for any reason before the function starts execution, it will not run at all.
  • The task will create a child tracing::Span with the specified name
  • The task will inherit all engine::TaskInheritedVariable instances from the current task.

For details on the various other overloads:

See also
flavors_of_async

For maximum customization of task parameters, see utils::TaskBuilder.

Parameters
nameName of the task to show in logs
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult
Examples
core/src/components/component_sample_test.cpp, and samples/tcp_full_duplex_service/main.cpp.

Definition at line 54 of file async.hpp.

◆ AsyncBackground()

template<typename Function, typename... Args>
auto utils::AsyncBackground ( std::string name,
engine::TaskProcessor & task_processor,
Function && f,
Args &&... args )
nodiscard

Starts an asynchronous task that inherits tracing::Span and only the engine::TaskInheritedVariable instances with engine::TaskInheritedVariablePriority::kBackground, including baggage::Baggage and OpenTelemetry tracing headers. Task execution may be cancelled before the function starts execution in case of engine::TaskProcessor overload.

Typically used from a request handler to launch tasks that outlive the request and do not effect its completion.

Usage example

Suppose you have some component that runs asynchronous tasks:

class AsyncRequestProcessor final {
public:
AsyncRequestProcessor();
void FooAsync(Request&& request);
Response WaitAndGetAggregate();
private:
static Response Foo(Request&& request);
engine::TaskProcessor& task_processor_;
concurrent::Variable<std::vector<engine::TaskWithResult<Response>>> tasks_;
};
auto handler = [&](Request&& request) {
async_request_processor.FooAsync(std::move(request));
return "Please wait, your request is being processed.";
};

If the tasks logically belong to the component itself (not to the method caller), then they should be launched using utils::AsyncBackground instead of the regular utils::Async

void AsyncRequestProcessor::FooAsync(Request&& request) {
auto tasks = tasks_.Lock();
tasks->push_back(utils::AsyncBackground("foo", task_processor_, &Foo, std::move(request)));
}

Arguments

By default, arguments are copied or moved inside the resulting TaskWithResult, like std::thread does. To pass an argument by reference, wrap it in std::ref / std::cref or capture the arguments using a lambda.

Parameters
nameName of the task to show in logs
task_processorTask processor to run on
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult

Definition at line 306 of file async.hpp.

◆ AsyncHideSpan() [1/2]

template<typename Function, typename... Args>
auto utils::AsyncHideSpan ( engine::TaskProcessor & task_processor,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Starts an asynchronous task with a hidden tracing::Span. The span has logging::Level::kNone log level, while logs within the span remain linked to the nearest visible span.

Task execution may be cancelled before the function starts execution in case of TaskProcessor overload.

Parameters
task_processorTask processor to run on
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult

Definition at line 124 of file async.hpp.

◆ AsyncHideSpan() [2/2]

template<typename Function, typename... Args>
auto utils::AsyncHideSpan ( Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Starts an asynchronous task with a hidden tracing::Span. The span has logging::Level::kNone log level, while logs within the span remain linked to the nearest visible span.

Task execution may be cancelled before the function starts execution in case of TaskProcessor overload.

Parameters
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult

Definition at line 100 of file async.hpp.

◆ AtomicMax()

template<typename T>
T utils::AtomicMax ( std::atomic< T > & atomic,
T value )

Concurrently safe sets atomic to a value if value is greater.

Note
Uses std::memory_order_relaxed

Definition at line 57 of file atomic.hpp.

◆ AtomicMin()

template<typename T>
T utils::AtomicMin ( std::atomic< T > & atomic,
T value )

Concurrently safe sets atomic to a value if value is less.

Note
Uses std::memory_order_relaxed

Definition at line 47 of file atomic.hpp.

◆ AtomicUpdate()

template<typename T, typename Func>
T utils::AtomicUpdate ( std::atomic< T > & atomic,
Func updater )

Atomically performs the operation of updater on atomic.

updater may be called multiple times per one call of AtomicUpdate, so it must be idempotent. To ensure that the function does not spin for a long time, updater must be fairly simple and fast.

Parameters
atomicthe variable to update
updatera lambda that takes the old value and produces the new value
Returns
The updated value
Note
Uses std::memory_order_relaxed

Definition at line 24 of file atomic.hpp.

◆ CollectInParallel()

template<std::ranges::input_range Range, typename Start>
requires std::invocable<const Start&, std::ranges::range_reference_t<Range>> && impl::CollectableFuture<std::invoke_result_t
<const Start&, std::ranges::range_reference_t<Range>>>
auto concurrent::CollectInParallel ( Range && input_range,
ParallelCollectSettings settings,
const Start & start ) -> std::vector< utils::expected< impl::CollectedValue< std::invoke_result_t< const Start &, std::ranges::range_reference_t< Range > > >, std::exception_ptr > >

Collect results from lazily started operations with bounded concurrency.

Maintains a sliding window of in-flight operations: whenever an operation is collected, its slot can be reused without waiting for earlier inputs. Calls start at most once per input, without retries. Duplicate inputs are processed independently.

Parameters
input_rangeInput range. Elements are forwarded to the factory as std::ranges::range_reference_t<Range> without copying or storing them.
settingsConcurrency limit and failure policy. See concurrent::ParallelCollectSettings.
startFactory invoked with each range element, preserving its reference type and value category, in the calling task. Returns an owning engine::Awaitable with a Get() or get() method, such as engine::TaskWithResult, engine::Future, or a generated HTTP response future. If both methods exist, Get() is used. The factory controls task creation, tracing, timeouts, and client retry settings.
Returns
A vector of utils::expected values in input order, each containing either the operation's result or a std::exception_ptr preserving the exception's dynamic type. Completion order does not affect result order. Supports void and move-only results. For a reusable input range, callers can associate inputs and results by index or zip them.
Failure handling
With concurrent::CollectFailurePolicy::kContinue, std::exception-based errors from the factory and Get()/get() are collected and all inputs are processed. With concurrent::CollectFailurePolicy::kFailFast, the first observed std::exception stops new launches. Pending operations receive RequestCancel() when available, otherwise Cancel() when available. Futures remain alive until all waits on their tokens have finished. Pending operations are awaited via engine::WaitAnyContext without retrieving their results. Task cancellation is blocked during cleanup. Errors from cancellation requests derived from std::exception are ignored; the original exception is rethrown and no partial results are returned. Future types do not need to provide Wait() or wait().
Warning
Fail-fast cleanup can still block while awaiting non-cancellable work or tasks that do not respond to cancellation. Configure operation timeouts in start.
Cancellation and lifetimes
Parent cancellation and non-std exceptions propagate under either policy. During stack unwinding, outstanding awaitables are destroyed according to their own RAII semantics. Work started by the factory must manage its lifetime accordingly. When capturing input references in asynchronous work, the caller must ensure that the referenced elements remain valid until that work finishes. Single-pass and lazy ranges may invalidate references when advanced; copy or move such inputs into the operation before the factory returns. A copied non-owning input (such as std::string_view) does not extend the lifetime of its referent.
Exceptions
`std::invalid_argument`If settings.max_parallel_tasks is zero, even for an empty range.
`std::exception`The first observed operation error in fail-fast mode, with its original dynamic type. Infrastructure errors may propagate under either policy.
Examples
Collecting move-only task results, including duplicate inputs:
const std::vector<int> inputs{7, 7, 3};
const auto results = CollectInParallel(inputs, {.max_parallel_tasks = 2}, [](int input) {
return utils::Async("move-only", [input] { return std::make_unique<int>(input * 2); });
});
ASSERT_EQ(results.size(), inputs.size());
int sevens = 0;
for (std::size_t index = 0; index < results.size(); ++index) {
ASSERT_TRUE(results[index].has_value());
EXPECT_EQ(*results[index].value(), inputs[index] * 2);
if (inputs[index] == 7) {
++sevens;
}
}
EXPECT_EQ(sevens, 2);
Collecting individual startup and task errors with the default continue policy (LookupError is the test's exception type):
const std::vector<int> inputs{0, 1, 2, 3};
std::array<int, 4> calls{};
const auto results = CollectInParallel(inputs, {.max_parallel_tasks = 2}, [&calls](int input) {
++calls[input];
if (input == 1) {
throw LookupError{};
}
return utils::Async("possibly-failing", [input] {
if (input == 2) {
throw LookupError{};
}
return input * 2;
});
});
ASSERT_EQ(results.size(), inputs.size());
for (std::size_t index = 0; index < results.size(); ++index) {
const auto input = inputs[index];
const auto& result = results[index];
EXPECT_EQ(calls[input], 1);
if (input == 1 || input == 2) {
ASSERT_FALSE(result.has_value());
EXPECT_THROW(std::rethrow_exception(result.error()), LookupError);
} else {
ASSERT_TRUE(result.has_value());
EXPECT_EQ(result.value(), input * 2);
}
}
Stopping on a startup error and skipping the remaining inputs:
const std::vector<int> inputs{0, 1, 2, 3};
engine::Promise<int> promise;
promise.set_value(0);
int launches = 0;
const auto start = [&promise, &launches](int input) {
++launches;
if (input == 1) {
throw LookupError{};
}
return promise.get_future();
};
EXPECT_THROW(
CollectInParallel(inputs, {.max_parallel_tasks = 2, .failure_policy = CollectFailurePolicy::kFailFast}, start),
LookupError
);
EXPECT_EQ(launches, 2);

Definition at line 277 of file collect_in_parallel.hpp.

◆ CriticalAsync() [1/2]

template<typename Function, typename... Args>
auto utils::CriticalAsync ( engine::TaskProcessor & task_processor,
std::string name,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Execution of function is guaranteed to start regardless of engine::TaskProcessor load limits. Prefer utils::Async by default.

Parameters
task_processorTask processor to run on
nameName for the tracing::Span to use with this task
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult
Examples
samples/ydb_service/components/federated_topic_reader.cpp, and samples/ydb_service/components/topic_reader.cpp.

Definition at line 147 of file async.hpp.

◆ CriticalAsync() [2/2]

template<typename Function, typename... Args>
auto utils::CriticalAsync ( std::string name,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Execution of function is guaranteed to start regardless of engine::TaskProcessor load limits. Prefer utils::Async by default.

Parameters
nameName for the tracing::Span to use with this task
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult

Definition at line 198 of file async.hpp.

◆ CriticalAsyncBackground()

template<typename Function, typename... Args>
auto utils::CriticalAsyncBackground ( std::string name,
engine::TaskProcessor & task_processor,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Execution of function is guaranteed to start regardless of engine::TaskProcessor load limits. Use for background tasks for which failing to start not just breaks handling of a single request, but harms the whole service instance.

Parameters
nameName of the task to show in logs
task_processorTask processor to run on
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::TaskWithResult

Definition at line 337 of file async.hpp.

◆ GetAll()

template<typename... Tasks>
auto engine::GetAll ( Tasks &... tasks)

Waits for the successful completion of all of the specified tasks or the cancellation of the caller.

Effectively performs for (auto& task : tasks) task.Get(); with a twist: task.Get() is called in tasks completion order rather than in provided order, thus exceptions are rethrown ASAP.

After successful return from this method the tasks are invalid, in case of an exception being thrown some of the tasks might be invalid.

Parameters
taskseither a single container, or a pack of future-like elements.
Returns
std::vector<Result> or void, depending on the tasks result type (which must be the same for all tasks).
Exceptions
WaitInterruptedExceptionwhen current_task::IsCancelRequested() and no TaskCancellationBlockers are present.
std::exceptionrethrows one of specified tasks exception, if any, in no particular order.
Note
Has overall computational complexity of O(N^2), where N is the number of tasks.
Prefer engine::WaitAllChecked for tasks with a result, unless you specifically need the results stored in a std::vector or when storing the results long-term.

Definition at line 84 of file get_all.hpp.

◆ MakeWaitAny()

template<typename... Awaitables>
WaitAnyContext engine::MakeWaitAny ( Awaitables &... awaitables)

Produces a WaitAnyContext for the given awaitables and sequences of awaitables.

Each passed awaitable could be either a single awaitable or a container of awaitables. In the latter case all awaitables from the container are appended to the context. The stored awaitables will have ids [0, GetNextId() - 1].

Definition at line 277 of file wait_any.hpp.

◆ SharedAsync() [1/2]

template<typename Function, typename... Args>
auto utils::SharedAsync ( engine::TaskProcessor & task_processor,
std::string name,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Task execution may be cancelled before the function starts execution in case of TaskProcessor overload.

Parameters
task_processorTask processor to run on
nameName of the task to show in logs
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::SharedTaskWithResult

Definition at line 176 of file async.hpp.

◆ SharedAsync() [2/2]

template<typename Function, typename... Args>
auto utils::SharedAsync ( std::string name,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Task execution may be cancelled before the function starts execution in case of TaskProcessor overload.

Parameters
nameName of the task to show in logs
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::SharedTaskWithResult

Definition at line 242 of file async.hpp.

◆ SharedCriticalAsync()

template<typename Function, typename... Args>
auto utils::SharedCriticalAsync ( std::string name,
Function && f,
Args &&... args )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Execution of function is guaranteed to start regardless of engine::TaskProcessor load limits. Prefer utils::SharedAsync by default.

Parameters
nameName for the tracing::Span to use with this task
fFunction to execute asynchronously
argsArguments to pass to the function
Returns
engine::SharedTaskWithResult

Definition at line 220 of file async.hpp.

◆ TryWaitForSubscribableFuture()

template<typename SubscribableFuture>
engine::FutureStatus drivers::TryWaitForSubscribableFuture ( SubscribableFuture && future,
engine::Deadline deadline )
nodiscard

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Returns
an error code if deadline is exceeded or task is cancelled
Warning
Repeatedly waiting again after deadline expiration leads to a memory leak, use drivers::SubscribableFutureWrapper instead.

Definition at line 97 of file subscribable_futures.hpp.

◆ WaitAllChecked()

template<typename... Tasks>
void engine::WaitAllChecked ( Tasks &... tasks)

Waits for the successful completion of all of the specified tasks or for the cancellation of the caller.

Effectively performs for (auto& task : tasks) task.Wait(); with a twist: if any task completes with an exception, it gets rethrown ASAP.

Invalid tasks are skipped.

Tasks are not invalidated by WaitAllChecked; the result can be retrieved after the call.

Parameters
taskseither a single container, or a pack of future-like elements.
Exceptions
WaitInterruptedExceptionwhen current_task::ShouldCancel() (for WaitAllChecked versions without a deadline)
std::exceptionone of specified tasks exception, if any, in no particular order.
Note
Has overall computational complexity of O(N), where N is the number of tasks.
Keeping the tasks valid may have a small extra memory impact. Make sure to drop the tasks after reading the results.
Prefer engine::GetAll for tasks without a result, unless you specifically need to keep the tasks alive for some reason.

Definition at line 94 of file wait_all_checked.hpp.

◆ WaitAny()

template<typename... Tasks>
std::optional< std::size_t > engine::WaitAny ( Tasks &... tasks)

Waits for the completion of any of the specified tasks or the cancellation of the caller.

Deprecated
WaitAny is deprecated. Please, prefer MakeWaitAny + WaitAnyContext::Wait.

Could be used to get the ready HTTP requests ASAP:

std::size_t ProcessReadyRequests(std::vector<clients::http::ResponseFuture>& requests, engine::Deadline deadline) {
std::size_t processed_requests = 0;
while (auto indx = engine::WaitAnyUntil(deadline, requests)) {
++processed_requests;
const std::shared_ptr<clients::http::Response> response = requests[*indx].Get();
EXPECT_TRUE(response->IsOk());
}
return processed_requests;
}

Works with different types of tasks and futures:

auto task0 = engine::AsyncNoTracing([] { return 1; });
auto task1 = utils::Async("long_task", [] {
return std::string{"abc"};
});
auto task_idx_opt = this->MakeWaitAnyProxy().WaitAny(task0, task1);
ASSERT_TRUE(task_idx_opt);
EXPECT_EQ(*task_idx_opt, 0);
Parameters
taskseither a single container, or a pack of future-like elements.
Returns
the index of the completed task, or std::nullopt if there are no completed tasks (possible if current task was cancelled).
Deprecated
WaitAnyFor is deprecated. Please, prefer MakeWaitAny + WaitAnyContext::WaitFor.
Deprecated
WaitAnyUntil is deprecated. Please, prefer MakeWaitAny + WaitAnyContext::WaitUntil.
Deprecated
WaitAnyUntil is deprecated. Please, prefer MakeWaitAny + WaitAnyContext::WaitUntil.

Definition at line 65 of file wait_any.hpp.

◆ WaitForSubscribableFuture()

template<typename SubscribableFuture>
void drivers::WaitForSubscribableFuture ( SubscribableFuture && future)

Waits on the given future as described on drivers::SubscribableFutureWrapper.

The result can be retrieved from the original future once ready.

Exceptions
engine::WaitInterruptedExceptionon task cancellation

Definition at line 86 of file subscribable_futures.hpp.