Async++ unknown
Async (co_await/co_return) code for C++
Loading...
Searching...
No Matches
simple_dispatcher.h
1#pragma once
2#include <asyncpp/dispatcher.h>
3
4#include <atomic>
5#include <condition_variable>
6#include <deque>
7#include <mutex>
8
9namespace asyncpp {
10
15 std::mutex m_mtx;
16 std::condition_variable m_cv;
17 std::deque<std::function<void()>> m_queue;
18 std::atomic<bool> m_done = false;
19
20 public:
25 void push(std::function<void()> cbfn) override {
26 if (!cbfn) return;
27 std::unique_lock lck{m_mtx};
28 m_queue.emplace_back(std::move(cbfn));
29 m_cv.notify_all();
30 }
31
35 void stop() noexcept {
36 std::unique_lock lck{m_mtx};
37 m_done = true;
38 m_cv.notify_all();
39 }
40
44 void run() {
45 dispatcher* const old_dispatcher = dispatcher::current(this);
46 while (!m_done) {
47 std::unique_lock lck{m_mtx};
48 if (m_queue.empty()) {
49 m_cv.wait(lck);
50 continue;
51 }
52 auto cbfn = std::move(m_queue.front());
53 m_queue.pop_front();
54 lck.unlock();
55 if (cbfn) cbfn();
56 }
57 dispatcher::current(old_dispatcher);
58 }
59 };
60} // namespace asyncpp
Basic dispatcher interface class.
Definition dispatcher.h:8
static dispatcher * current() noexcept
Definition dispatcher.h:48
A very basic dispatcher that runs in a single thread until manually stopped.
Definition simple_dispatcher.h:14
void run()
Block and process tasks pushed to it until stop is called.
Definition simple_dispatcher.h:44
void stop() noexcept
Stop the dispatcher. It will return the on the next iteration, regardless if there is any work left.
Definition simple_dispatcher.h:35
void push(std::function< void()> cbfn) override
Push a function to be executed on the dispatcher.
Definition simple_dispatcher.h:25