Photon 1.0.0
Loading...
Searching...
No Matches
periodic_worker.h
Go to the documentation of this file.
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
18{
19 namespace details
20 {
21
23 {
24 public:
25 template <typename Rep, typename Period>
26 periodic_worker(const std::function<void()>& callback_fun, std::chrono::duration<Rep, Period> interval)
27 {
28 active_ = (interval > std::chrono::duration<Rep, Period>::zero());
29 if (!active_)
30 {
31 return;
32 }
33
34 worker_thread_ = std::thread([this, callback_fun, interval]() {
35 for (;;)
36 {
37 std::unique_lock<std::mutex> lock(this->mutex_);
38 if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
39 {
40 return; // active_ == false, so exit this thread
41 }
42 callback_fun();
43 }
44 });
45 }
48 // stop the worker thread and join it
50
51 private:
52 bool active_;
53 std::thread worker_thread_;
54 std::mutex mutex_;
55 std::condition_variable cv_;
56 };
57 } // namespace details
58} // namespace spdlog
59
60#ifdef SPDLOG_HEADER_ONLY
61#include "periodic_worker-inl.h"
62#endif
Definition periodic_worker.h:23
std::thread worker_thread_
Definition periodic_worker.h:53
std::mutex mutex_
Definition periodic_worker.h:54
periodic_worker(const periodic_worker &)=delete
bool active_
Definition periodic_worker.h:52
periodic_worker(const std::function< void()> &callback_fun, std::chrono::duration< Rep, Period > interval)
Definition periodic_worker.h:26
periodic_worker & operator=(const periodic_worker &)=delete
std::condition_variable cv_
Definition periodic_worker.h:55
#define SPDLOG_API
Definition common.h:45
Definition async.h:26
annotation details
Definition tag_strings.h:125