Skip to content

Instantly share code, notes, and snippets.

@yujincheng08
Last active June 1, 2019 03:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yujincheng08/c9078bfb8a975a28db79429dc7f6826a to your computer and use it in GitHub Desktop.
Save yujincheng08/c9078bfb8a975a28db79429dc7f6826a to your computer and use it in GitHub Desktop.
Thread safe c++ Timer
#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