Last active
June 1, 2019 03:44
-
-
Save yujincheng08/c9078bfb8a975a28db79429dc7f6826a to your computer and use it in GitHub Desktop.
Thread safe c++ Timer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <condition_variable> | |
#include <functional> | |
#include <memory> | |
#include <shared_mutex> | |
#include <thread> | |
#include <chrono> | |
template <class Rep, class Period> class Timer { | |
public: | |
using Callback = std::function<void()>; | |
Timer(const std::chrono::duration<Rep, Period> &duration, | |
const Callback &callback) { | |
std::thread([=]() { | |
std::mutex mutex; | |
std::unique_lock lk(mutex); | |
do { | |
std::thread([=]() { | |
std::shared_lock lk(*mutex_); | |
callback(); | |
}).detach(); | |
} while (!cv_->wait_for(lk, duration, [=]() { return *stop_; })); | |
}).detach(); | |
} | |
void Stop(bool sync = false) { | |
*stop_ = true; | |
cv_->notify_all(); | |
if (sync) { | |
std::unique_lock lk(*mutex_); | |
} | |
} | |
~Timer() { Stop(true); } | |
private: | |
std::shared_ptr<std::condition_variable> cv_{ | |
std::make_shared<std::condition_variable>()}; | |
std::shared_ptr<bool> stop_{std::make_shared<bool>(false)}; | |
std::shared_ptr<std::shared_mutex> mutex_{ | |
std::make_shared<std::shared_mutex>()}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment