periodic_worker.h 1.8 KB

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