std::this_thread::sync_wait
| Defined in header <execution>
|
||
namespace this_thread {
struct /* unspecified */ sync_wait_t;
}
|
(1) | (since C++26) |
namespace this_thread {
inline constexpr /* unspecified */ sync_wait{};
}
|
(2) | (since C++26) (customization point object) |
| Call signature |
||
auto this_thread::sync_wait( execution::sender auto sndr )
-> std::optional<std::tuple</*value-types-of-sndr*/...>>;
|
(3) | (since C++26) |
Starts a sender and blocks the calling thread until it has completed, then returns the result: the values as an engaged std::optional of a std::tuple, an exception if the sender failed, or an empty optional if it was cancelled.
sync_wait is how a program leaves the world of senders: schedule and just are the ways in, and sync_wait is one way out, back to ordinary code. It is typically used in main, in tests, and in synchronous code that needs the result of asynchronous work. The sender is started on the calling thread, which also runs a small event loop for the duration of the call, so work that the sender schedules back onto its environment's scheduler runs on the calling thread while it waits.
Parameters
| sndr | - | the sender to start and wait for; it must complete with exactly one set of values (for senders with several, use this_thread::sync_wait_with_variant) |
Return value
The result of the sender, by how it completed:
- If
sndrcompletes with values, an engaged std::optional holding a std::tuple of the values. With one valuevof typeT, the result isstd::optional<std::tuple<T>>, usually taken apart withauto [v] = sync_wait(sndr).value();. With no values, it is anstd::optional<std::tuple<>>. - If
sndrcompletes with an error, an exception is thrown fromsync_wait: an std::exception_ptr is rethrown as the original exception, a std::error_code is thrown as a std::system_error, and an error of any other type is thrown as an exception object of that type. - If
sndrcompletes with the stopped signal (it was cancelled), an empty std::optional is returned.
The call is ill-formed if sndr does not satisfy execution::sender_in for the environment that sync_wait provides, or if it can complete with more than one set of values. This is diagnosed at compile time.
Customization point objects
The name execution::sync_wait denotes a customization point object, which is a const function object of a literal semiregular class type. The cv-unqualified version of its type is a tag type denoted as execution::sync_wait_t. See CustomizationPointObject for details.
Details
- The sender is connected to a receiver whose environment provides a scheduler (and a start scheduler and a delegation scheduler) backed by a run_loop that is driven by the calling thread. A sender that reads the scheduler out of the environment with read_env and schedules work on it therefore runs that work on the calling thread, inside the call.
- The call blocks the thread with forward progress delegation: the thread keeps running the work handed to it while it waits, instead of just sleeping, so work that depends on the calling thread cannot deadlock.
- The environment that
sync_waitprovides contains schedulers only, no stop token:sync_waitnever requests a stop. The sender can still complete with the stopped signal on its own, in which case an empty optional is returned.
Notes
- It is specified in
std::this_thread, not instd::execution, on purpose:sync_waithas to block the current execution agent, and the only functions the standard has for acting on the current agent are those instd::this_thread. If C++ ever gets other kinds of execution agents, such as fibers, a flavor in a matching namespace (for examplestd::this_fiber::sync_wait) is expected, and other runtimes may provide their own, for agents that block in a different way. - To get several different value types, or a result of a sender that could complete in more than one way, use sync_wait_with_variant, which wraps the result in a std::variant of std::tuples. To turn an error or cancellation into a value first, use upon_error, upon_stopped or stopped_as_optional.
- Blocking in
sync_waitties up the thread. Use it at the edges of a program, not in the middle of asynchronous code, where it blocks one of the threads that the asynchronous work may need.
Example
A computation runs on a worker thread, and the calling thread blocks in sync_wait until it is done. The first call returns the value. In the second, the computation throws, and sync_wait throws the exception to the caller.
The standard header is not available in the online compilers yet, so this link runs the example on Compiler Explorer with stdexec, the reference implementation.
#include <execution>
#include <print>
#include <stdexcept>
#include <thread>
namespace ex = std::execution;
// An event loop on its own thread; the destructor finishes the loop so that the
// thread can be joined, also when an exception is propagating.
struct loop_thread
{
ex::run_loop loop;
std::jthread thread;
loop_thread() : thread([this] { loop.run(); }) {}
~loop_thread() { loop.finish(); }
};
ex::sender auto compute(ex::scheduler auto sched, int n)
{
return ex::schedule(sched)
| ex::then([n]
{
if (n < 0)
throw std::invalid_argument("negative input");
return n * n;
});
}
int main()
{
loop_thread worker;
// Blocks until the worker has finished; the value comes back in an optional tuple.
auto [square] = std::this_thread::sync_wait(compute(worker.loop.get_scheduler(), 7)).value();
std::println("7 squared is {}", square);
// An error completion is thrown as an exception.
try
{
std::this_thread::sync_wait(compute(worker.loop.get_scheduler(), -1));
}
catch (const std::invalid_argument& e)
{
std::println("failed: {}", e.what());
}
}
Output:
7 squared is 49
failed: negative input
See also
(C++26) |
adapts a sender that can complete with several different sets of values into one that completes with a single std::variant of tuples (customization point object) |
(C++26) |
creates a sender that queries its receiver's associated environment (customization point object) |
(C++26) |
execution resource holding a thread-safe MPSC task queue and a manually-driven event loop (class) |