Livox SDK API  V2.2.0
periodic_worker.h
Go to the documentation of this file.
1 
2 //
3 // Copyright(c) 2018 Gabi Melman.
4 // Distributed under the MIT License (http://opensource.org/licenses/MIT)
5 //
6 
7 #pragma once
8 
9 // periodic worker thread - periodically executes the given callback function.
10 //
11 // RAII over the owned thread:
12 // creates the thread on construction.
13 // stops and joins the thread on destruction (if the thread is executing a callback, wait for it to finish first).
14 
15 #include <chrono>
16 #include <condition_variable>
17 #include <functional>
18 #include <mutex>
19 #include <thread>
20 namespace spdlog {
21 namespace details {
22 
24 {
25 public:
26  periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval)
27  {
28  active_ = (interval > std::chrono::seconds::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  }
46 
47  periodic_worker(const periodic_worker &) = delete;
48  periodic_worker &operator=(const periodic_worker &) = delete;
49 
50  // stop the worker thread and join it
52  {
53  if (worker_thread_.joinable())
54  {
55  {
56  std::lock_guard<std::mutex> lock(mutex_);
57  active_ = false;
58  }
59  cv_.notify_one();
60  worker_thread_.join();
61  }
62  }
63 
64 private:
65  bool active_;
66  std::thread worker_thread_;
67  std::mutex mutex_;
68  std::condition_variable cv_;
69 };
70 } // namespace details
71 } // namespace spdlog
periodic_worker(const std::function< void()> &callback_fun, std::chrono::seconds interval)
Definition: async.h:27
periodic_worker & operator=(const periodic_worker &)=delete