Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-30 10:24:43

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 to finish first).
0011 
0012 #include <chrono>
0013 #include <condition_variable>
0014 #include <functional>
0015 #include <mutex>
0016 #include <thread>
0017 namespace spdlog {
0018 namespace details {
0019 
0020 class SPDLOG_API periodic_worker
0021 {
0022 public:
0023     template<typename Rep, typename Period>
0024     periodic_worker(const std::function<void()> &callback_fun, std::chrono::duration<Rep, Period> interval)
0025     {
0026         active_ = (interval > std::chrono::duration<Rep, Period>::zero());
0027         if (!active_)
0028         {
0029             return;
0030         }
0031 
0032         worker_thread_ = std::thread([this, callback_fun, interval]() {
0033             for (;;)
0034             {
0035                 std::unique_lock<std::mutex> lock(this->mutex_);
0036                 if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
0037                 {
0038                     return; // active_ == false, so exit this thread
0039                 }
0040                 callback_fun();
0041             }
0042         });
0043     }
0044     periodic_worker(const periodic_worker &) = delete;
0045     periodic_worker &operator=(const periodic_worker &) = delete;
0046     // stop the worker thread and join it
0047     ~periodic_worker();
0048 
0049 private:
0050     bool active_;
0051     std::thread worker_thread_;
0052     std::mutex mutex_;
0053     std::condition_variable cv_;
0054 };
0055 } // namespace details
0056 } // namespace spdlog
0057 
0058 #ifdef SPDLOG_HEADER_ONLY
0059 #    include "periodic_worker-inl.h"
0060 #endif