periodic_worker.h 1.7 KB

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