Template:cpp/execution/hello world example
From cppreference.com
simple wrapper for std::execution::run_loop that constantly polls run_loop's queue on a single dedicated thread. Demo using draft reference implementation: https://godbolt.org/z/a89Y1WKxd
Run this code
#include <execution> #include <thread> #include <iostream> class single_thread_context { std::execution::run_loop loop_; std::thread thread_; public: single_thread_context() : loop_() , thread_([this] { loop_.run(); }) {} single_thread_context(single_thread_context&&) = delete; ~single_thread_context() { loop_.finish(); thread_.join(); } std::execution::scheduler auto get_scheduler() noexcept { return loop_.get_scheduler(); } std::thread::id get_thread_id() const noexcept { return thread_.get_id(); } }; int main() { single_thread_context ctx; std::execution::sender auto snd = std::execution::schedule(ctx.get_scheduler()) | std::execution::then( []{ std::cout << "Hello world! Have an int.\n"; return 13; } ) | std::execution::then( [](int arg) { return arg + 42; }); auto [i] = std::this_thread::sync_wait(snd).value(); std::cout << "Back in the main thread, result is " << i << '\n'; }
Output:
Hello world! Have an int. Back in the main thread, result is 55