10#include <sys/syscall.h>
15#if defined(__GLIBC__) && (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 30))
16#include <sys/syscall.h>
17static inline pid_t gettid() {
return static_cast<pid_t
>(syscall(SYS_gettid)); }
26static inline bool is_main_thread() {
return gettid() == getpid(); }
27#elif defined(__APPLE__)
28static inline bool is_main_thread() {
return pthread_main_np() != 0; }
30#warning "is_main_thread() not implemented"
31static inline bool is_main_thread() {
return false; }
42 worker() : done(
false), terminated(
false) {}
48 std::scoped_lock lock(mutex);
56 template <
typename F,
typename... Args>
57 auto post(F &&f, Args &&...args) -> std::future<std::invoke_result_t<F, Args...>> {
58 using ReturnType = std::invoke_result_t<F, Args...>;
60 auto task = std::make_shared<std::packaged_task<ReturnType()>>(
61 [f = std::move(f), ... args = std::move(args)]() {
return f(args...); });
62 std::future<ReturnType> result = task->get_future();
65 std::scoped_lock lock(mutex);
66 tasks.emplace([task]() { (*task)(); });
78 if (!is_main_thread()) {
79 throw std::runtime_error(
"Worker can only run on main thread");
82 std::function<void()> task;
84 std::unique_lock<std::mutex> lock(mutex);
85 cv.wait(lock, [&]() {
return done.load() || !tasks.empty(); });
86 if (done.load() && tasks.empty())
88 task = std::move(tasks.front());
98 std::condition_variable cv;
99 std::queue<std::function<void()>> tasks;
100 std::atomic<bool> done;
101 std::atomic<bool> terminated;
Single-threaded Postgres workload worker.
Definition: threading.hpp:41
void run()
Run the worker.
Definition: threading.hpp:77