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 to finish first).
11
12#include <chrono>
13#include <condition_variable>
14#include <functional>
15#include <mutex>
16#include <thread>
17namespace spdlog {
18namespace details {
19
20class SPDLOG_API periodic_worker
21{
22public:
23 template<typename Rep, typename Period>
24 periodic_worker(const std::function<void()> &callback_fun, std::chrono::duration<Rep, Period> interval)
25 {
26 active_ = (interval > std::chrono::duration<Rep, Period>::zero());
27 if (!active_)
28 {
29 return;
30 }
31
32 worker_thread_ = std::thread([this, callback_fun, interval]() {
33 for (;;)
34 {
35 std::unique_lock<std::mutex> lock(this->mutex_);
36 if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
37 {
38 return; // active_ == false, so exit this thread
39 }
40 callback_fun();
41 }
42 });
43 }
44 periodic_worker(const periodic_worker &) = delete;
45 periodic_worker &operator=(const periodic_worker &) = delete;
46 // stop the worker thread and join it
47 ~periodic_worker();
48
49private:
50 bool active_;
51 std::thread worker_thread_;
52 std::mutex mutex_;
53 std::condition_variable cv_;
54};
55} // namespace details
56} // namespace spdlog
57
58#ifdef SPDLOG_HEADER_ONLY
59# include "periodic_worker-inl.h"
60#endif
61