MostlyHarmless 0.0.1
Loading...
Searching...
No Matches
mostlyharmless_TaskThread.h
Go to the documentation of this file.
1//
2// Created by Syl on 12/08/2024.
3//
4
5#ifndef MOSTLYHARMLESS_MOSTLYHARMLESS_TASKTHREAD_H
6#define MOSTLYHARMLESS_MOSTLYHARMLESS_TASKTHREAD_H
7#include <functional>
8#include <atomic>
9#include <mutex>
10#include <thread>
11
13 /***
14 * \brief Convenience wrapper around std::thread
15 *
16 * Contains some simple signalling mechanisms, and forms the basis for `Timer` - to use it, supply a lambda to the `action` field, then call perform (and remember to call `stop` to join the thread!)
17 */
18 class TaskThread {
19 public:
23 ~TaskThread() noexcept;
24
28 auto perform() -> void;
29
33 auto stop() noexcept -> void;
34
40 auto sleep() -> void;
41
45 auto wake() -> void;
46
51 auto signalStop() -> void;
52
57 [[nodiscard]] auto hasSignalledStop() const noexcept -> bool;
58
65 [[nodiscard]] auto isThreadRunning() const noexcept -> bool;
66
70 std::function<void(void)> action{ nullptr };
71
72 private:
73 auto reset() -> void;
74 struct {
75 std::mutex mutex;
76 std::atomic<bool> canWakeUp{ false };
77 std::condition_variable conditionVariable;
78 } m_sleepState;
79 std::atomic<bool> m_isThreadRunning{ false };
80 std::atomic<bool> m_stop{ false };
81 std::unique_ptr<std::thread> m_thread{ nullptr };
82 };
83} // namespace mostly_harmless::utils
84#endif // MOSTLYHARMLESS_MOSTLYHARMLESS_TASKTHREAD_H
Definition mostlyharmless_TaskThread.h:18
std::function< void(void)> action
Definition mostlyharmless_TaskThread.h:70
auto stop() noexcept -> void
std::atomic< bool > canWakeUp
Definition mostlyharmless_TaskThread.h:76
auto isThreadRunning() const noexcept -> bool
auto hasSignalledStop() const noexcept -> bool
std::mutex mutex
Definition mostlyharmless_TaskThread.h:75
std::condition_variable conditionVariable
Definition mostlyharmless_TaskThread.h:77
Contains general purpose utility classes & functions.
Definition mostlyharmless_TaskThread.h:12