diff options
Diffstat (limited to 'vespalib/src/vespa/vespalib/util/thread.h')
-rw-r--r-- | vespalib/src/vespa/vespalib/util/thread.h | 56 |
1 files changed, 26 insertions, 30 deletions
diff --git a/vespalib/src/vespa/vespalib/util/thread.h b/vespalib/src/vespa/vespalib/util/thread.h index c03f1c6e65c..6db1c1d54b4 100644 --- a/vespalib/src/vespa/vespalib/util/thread.h +++ b/vespalib/src/vespa/vespalib/util/thread.h @@ -2,46 +2,42 @@ #pragma once -#include "gate.h" #include "runnable.h" -#include "active.h" -#include <atomic> #include <thread> +#include <concepts> namespace vespalib { /** - * Abstraction of the concept of running a single thread. + * Thin thread abstraction that takes some things from std::thread + * (not allowed to assign to a running thread), some things from + * std::jthread (destructor does automatic join) and some things from + * now deprecated thread pools (the join function can be called + * multiple times and will only join the underlying thread if it is + * joinable). Enables starting a thread either by using a runnable and + * an init function or by forwarding directly to the std::thread + * constructor. Note that this class does not handle cancellation. **/ -class Thread : public Active +class Thread { private: - using init_fun_t = Runnable::init_fun_t; - static __thread Thread *_currentThread; - - Runnable &_runnable; - init_fun_t _init_fun; - vespalib::Gate _start; - std::mutex _lock; - std::condition_variable _cond; - std::atomic<bool> _stopped; - bool _woken; - std::jthread _thread; - - void run(); - + std::thread _thread; + Thread(std::thread &&thread) noexcept : _thread(std::move(thread)) {} public: - Thread(Runnable &runnable, init_fun_t init_fun_in); - ~Thread() override; - void start() override; - Thread &stop() override; - void join() override; - [[nodiscard]] bool stopped() const noexcept { - return _stopped.load(std::memory_order_relaxed); - } - bool slumber(double s); - static Thread ¤tThread(); - static void sleep(size_t ms); + Thread() noexcept : _thread() {} + Thread(const Thread &rhs) = delete; + Thread(Thread &&rhs) noexcept : Thread(std::move(rhs._thread)) {} + std::thread::id get_id() const noexcept { return _thread.get_id(); } + Thread &operator=(const Thread &rhs) = delete; + Thread &operator=(Thread &&rhs) noexcept; + void join(); + ~Thread(); + [[nodiscard]] static Thread start(Runnable &runnable, Runnable::init_fun_t init_fun_t); + template<typename F, typename... Args> + requires std::invocable<F,Args...> + [[nodiscard]] static Thread start(F &&f, Args && ... args) { + return Thread(std::thread(std::forward<F>(f), std::forward<Args>(args)...)); + }; }; } // namespace vespalib |