Namespaces
Variants
Views
Actions

Template:cpp/execution/hello world example

From cppreference.com
Revision as of 18:33, 3 October 2024 by Cubbi (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

#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