source: trunk/GDE/SINA/builddir/include/spdlog/details/periodic_worker.h

Last change on this file was 19170, checked in by westram, 2 years ago
  • sina source
    • unpack + remove tarball
    • no longer ignore sina builddir.
File size: 1.8 KB
Line 
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>
20namespace spdlog {
21namespace details {
22
23class periodic_worker
24{
25public:
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
51    ~periodic_worker()
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
64private:
65    bool active_;
66    std::thread worker_thread_;
67    std::mutex mutex_;
68    std::condition_variable cv_;
69};
70} // namespace details
71} // namespace spdlog
Note: See TracBrowser for help on using the repository browser.