1 | // Copyright(c) 2015-present, Gabi Melman & spdlog contributors. |
2 | // Distributed under the MIT License (http://opensource.org/licenses/MIT) |
3 | |
4 | #pragma once |
5 | |
6 | // periodic worker thread - periodically executes the given callback function. |
7 | // |
8 | // RAII over the owned thread: |
9 | // creates the thread on construction. |
10 | // stops and joins the thread on destruction (if the thread is executing a callback, wait for it |
11 | // to finish first). |
12 | |
13 | #include <chrono> |
14 | #include <condition_variable> |
15 | #include <functional> |
16 | #include <mutex> |
17 | #include <thread> |
18 | namespace spdlog { |
19 | namespace details { |
20 | |
21 | class SPDLOG_API periodic_worker { |
22 | public: |
23 | template <typename Rep, typename Period> |
24 | periodic_worker(const std::function<void()> &callback_fun, |
25 | std::chrono::duration<Rep, Period> interval) { |
26 | active_ = (interval > std::chrono::duration<Rep, Period>::zero()); |
27 | if (!active_) { |
28 | return; |
29 | } |
30 | |
31 | worker_thread_ = std::thread([this, callback_fun, interval]() { |
32 | for (;;) { |
33 | std::unique_lock<std::mutex> lock(this->mutex_); |
34 | if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; })) { |
35 | return; // active_ == false, so exit this thread |
36 | } |
37 | callback_fun(); |
38 | } |
39 | }); |
40 | } |
41 | std::thread &get_thread() { return worker_thread_; } |
42 | periodic_worker(const periodic_worker &) = delete; |
43 | periodic_worker &operator=(const periodic_worker &) = delete; |
44 | // stop the worker thread and join it |
45 | ~periodic_worker(); |
46 | |
47 | private: |
48 | bool active_; |
49 | std::thread worker_thread_; |
50 | std::mutex mutex_; |
51 | std::condition_variable cv_; |
52 | }; |
53 | } // namespace details |
54 | } // namespace spdlog |
55 | |
56 | #ifdef SPDLOG_HEADER_ONLY |
57 | #include "periodic_worker-inl.h" |
58 | #endif |
59 | |