Path: blob/master/cpp/linux/scheduler/InterruptableSleep.h
644 views
#pragma once12#include <chrono>3#include <thread>4#include <future>5#include <mutex>6#include <sstream>78namespace Bosma {9class InterruptableSleep {1011using Clock = std::chrono::system_clock;1213// InterruptableSleep offers a sleep that can be interrupted by any thread.14// It can be interrupted multiple times15// and be interrupted before any sleep is called (the sleep will immediately complete)16// Has same interface as condition_variables and futures, except with sleep instead of wait.17// For a given object, sleep can be called on multiple threads safely, but is not recommended as behaviour is undefined.1819public:20InterruptableSleep() : interrupted(false) {21}2223InterruptableSleep(const InterruptableSleep &) = delete;2425InterruptableSleep(InterruptableSleep &&) noexcept = delete;2627~InterruptableSleep() noexcept = default;2829InterruptableSleep &operator=(const InterruptableSleep &) noexcept = delete;3031InterruptableSleep &operator=(InterruptableSleep &&) noexcept = delete;3233void sleep_for(Clock::duration duration) {34std::unique_lock<std::mutex> ul(m);35cv.wait_for(ul, duration, [this] { return interrupted; });36interrupted = false;37}3839void sleep_until(Clock::time_point time) {40std::unique_lock<std::mutex> ul(m);41cv.wait_until(ul, time, [this] { return interrupted; });42interrupted = false;43}4445void sleep() {46std::unique_lock<std::mutex> ul(m);47cv.wait(ul, [this] { return interrupted; });48interrupted = false;49}5051void interrupt() {52std::lock_guard<std::mutex> lg(m);53interrupted = true;54cv.notify_one();55}5657private:58bool interrupted;59std::mutex m;60std::condition_variable cv;61};62}636465