Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-07-14 09:07:58

0001 // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
0002 // Distributed under the MIT License (http://opensource.org/licenses/MIT)
0003 
0004 #pragma once
0005 
0006 // periodic worker thread - periodically executes the given callback function.
0007 //
0008 // RAII over the owned thread:
0009 //    creates the thread on construction.
0010 //    stops and joins the thread on destruction (if the thread is executing a callback, wait for it
0011 //    to finish first).
0012 
0013 #include <chrono>
0014 #include <condition_variable>
0015 #include <functional>
0016 #include <mutex>
0017 #include <thread>
0018 namespace spdlog {
0019 namespace details {
0020 
0021 class SPDLOG_API periodic_worker {
0022 public:
0023     template <typename Rep, typename Period>
0024     periodic_worker(const std::function<void()> &callback_fun,
0025                     std::chrono::duration<Rep, Period> interval) {
0026         active_ = (interval > std::chrono::duration<Rep, Period>::zero());
0027         if (!active_) {
0028             return;
0029         }
0030 
0031         worker_thread_ = std::thread([this, callback_fun, interval]() {
0032             for (;;) {
0033                 std::unique_lock<std::mutex> lock(this->mutex_);
0034                 if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; })) {
0035                     return;  // active_ == false, so exit this thread
0036                 }
0037                 callback_fun();
0038             }
0039         });
0040     }
0041     std::thread &get_thread() { return worker_thread_; }
0042     periodic_worker(const periodic_worker &) = delete;
0043     periodic_worker &operator=(const periodic_worker &) = delete;
0044     // stop the worker thread and join it
0045     ~periodic_worker();
0046 
0047 private:
0048     bool active_;
0049     std::thread worker_thread_;
0050     std::mutex mutex_;
0051     std::condition_variable cv_;
0052 };
0053 }  // namespace details
0054 }  // namespace spdlog
0055 
0056 #ifdef SPDLOG_HEADER_ONLY
0057     #include "periodic_worker-inl.h"
0058 #endif