10#include <sys/syscall.h>
19static inline bool is_main_thread() {
return gettid() == getpid(); }
20#elif defined(__APPLE__)
21static inline bool is_main_thread() {
return pthread_main_np() != 0; }
23#warning "is_main_thread() not implemented"
24static inline bool is_main_thread() {
return false; }
35 worker() : done(
false), terminated(
false) {}
41 std::scoped_lock lock(mutex);
49 template <
typename F,
typename... Args>
50 auto post(F &&f, Args &&...args) -> std::future<std::invoke_result_t<F, Args...>> {
51 using ReturnType = std::invoke_result_t<F, Args...>;
53 auto task = std::make_shared<std::packaged_task<ReturnType()>>(
54 [f = std::move(f), ... args = std::move(args)]() {
return f(args...); });
55 std::future<ReturnType> result = task->get_future();
58 std::scoped_lock lock(mutex);
59 tasks.emplace([task]() { (*task)(); });
71 if (!is_main_thread()) {
72 throw std::runtime_error(
"Worker can only run on main thread");
75 std::function<void()> task;
77 std::unique_lock<std::mutex> lock(mutex);
78 cv.wait(lock, [&]() {
return done.load() || !tasks.empty(); });
79 if (done.load() && tasks.empty())
81 task = std::move(tasks.front());
91 std::condition_variable cv;
92 std::queue<std::function<void()>> tasks;
93 std::atomic<bool> done;
94 std::atomic<bool> terminated;
Single-threaded Postgres workload worker.
Definition: threading.hpp:34
void run()
Run the worker.
Definition: threading.hpp:70