Skip to content

Instantly share code, notes, and snippets.

@kgbook
Last active April 19, 2019 09:09
Show Gist options
  • Save kgbook/eb956222d7bb04470af11a20be567979 to your computer and use it in GitHub Desktop.
Save kgbook/eb956222d7bb04470af11a20be567979 to your computer and use it in GitHub Desktop.
#thread_sleep #interrupt_sleep
//
// Created by kang on 2019-04-19.
//
#include <chrono>
#include <iostream>
#include "interrupt_sleep.h"
using namespace std::chrono;
InterruptSleep::InterruptSleep() : terminate_sleep(false) {}
void InterruptSleep::interrupt(bool enable) {
std::unique_lock<std::mutex> lock(mutex_);
terminate_sleep = enable;
lock.unlock();
cond_.notify_all();
}
bool InterruptSleep::sleep(uint32_t ms) {
milliseconds sleep_duration_ms(ms);
std::unique_lock<std::mutex> lock(mutex_);
return !cond_.wait_for(lock, sleep_duration_ms, [this](){
if (terminate_sleep) {
std::cout <<"terminate_sleep!!!" <<std::endl;
}
return terminate_sleep;
});
}
//
// Created by kang on 2019-04-19.
//
#ifndef SLEEP_INTERRUPT_INTERRUPT_SLEEP_H
#define SLEEP_INTERRUPT_INTERRUPT_SLEEP_H
#include <mutex>
class InterruptSleep {
public:
InterruptSleep();
virtual ~InterruptSleep() = default;
void interrupt(bool enable);
bool sleep(uint32_t ms);
private:
std::condition_variable cond_;
std::mutex mutex_;
bool terminate_sleep;
};
#endif //SLEEP_INTERRUPT_INTERRUPT_SLEEP_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment