如何在C++中實(shí)現(xiàn)一個(gè)正確的時(shí)間循環(huán)器詳解
前言
實(shí)際工程中可能會(huì)有這樣一類(lèi)普遍需求:在服務(wù)中,單獨(dú)起一個(gè)線程,以一個(gè)固定的時(shí)間間隔,周期性地完成特定的任務(wù)。我們把這種問(wèn)題抽象成一個(gè)時(shí)間循環(huán)器。
Naive Way
class TimerCircle { private: std::atomic_bool running_{false}; uint64_t sleep_{0UL}; std::thread thread_; public: explicit TimerCircle(uint64_t s) : sleep_{s} {} ~TimerCircle() { if (thread_.joinable()) { terminate(); thread_.join(); } } TimerCircle(const TimerCircle&) = delete; TimerCircle& operator=(const TimerCircle&) = delete; TimerCircle(TimerCircle&&) = default; TimerCircle& operator=(TimerCircle&&) = default; public: void launch() { thread_ = std::move(std::thread(&TimerCircle::loop, this)); } void terminate() { running_.store(false); } void loop() { running_.store(true); while (running_.load()) { do_something(); std::this_thread::sleep_for(std::chrono::seconds(sleep_)); } } private: void do_something() const = 0; };
實(shí)現(xiàn)簡(jiǎn)單平凡,一眼就能看出來(lái)沒(méi)啥問(wèn)題,于是也沒(méi)啥好說(shuō)的。
細(xì)節(jié)里的魔鬼
唯一的魔鬼藏在細(xì)節(jié)里。如果 TimerCircle 類(lèi)型的對(duì)象發(fā)生析構(gòu),那么析構(gòu)該對(duì)象的線程最多會(huì)被阻塞 sleep_ 秒。如果周期很長(zhǎng),比如長(zhǎng)達(dá) 6 小時(shí),那這顯然是不可接受。
為此,我們需要借助標(biāo)準(zhǔn)庫(kù)的條件變量 std::condition_variable 的 wait_for 函數(shù)的幫助。首先看其函數(shù)簽名
template <typename Rep, typename Period, typename Predicate> bool wait_for(std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time, Predicate pred);
函數(shù)接受三個(gè)參數(shù)。lock 是一個(gè) unique_lock,它必須為調(diào)用 wait_for 的線程所鎖住;rel_time 是一個(gè)時(shí)間段,表示超時(shí)時(shí)間;pred 是一個(gè)謂詞,它要么返回 true 要么返回 false。
一旦調(diào)用,函數(shù)會(huì)阻塞當(dāng)前線程,直到兩種情況返回:
- 超時(shí);此時(shí)函數(shù)返回 pred()。
- 條件變量被通知,且謂詞返回 true;此時(shí)函數(shù)返回 true。
于是我們可以實(shí)現(xiàn)一個(gè) Countdown 類(lèi)
#include <chrono> #include <condition_variable> #include <mutex> class Countdown final { private: bool running_ = true; mutable std::mutex mutex_; mutable std::condition_variable cv_; public: Countdown() = default; ~Countdown() = default; Countdown(const Countdown&) = delete; Countdown& operator=(const Countdown&) = delete; Countdown(Countdown&&) = delete; Countdown& operator=(Countdown&&) = delete; public: void terminate() { { std::lock_guard<std::mutex> lock(mutex_); running_ = false; } cv_.notify_all(); } template <typename Rep, typename Peroid> bool wait_for(std::chrono::duration<Rep, Peroid>&& duration) const { std::unique_lock<std::mutex> lock(mutex_); bool terminated = cv_.wait_for(lock, duration, [&]() { return !running_; }); return !terminated; } };
于是,TimerCircle 就變成
class TimerCircle { private: uint64_t sleep_{0UL}; Countdown cv_; std::thread thread_; public: explicit TimerCircle(uint64_t s) : sleep_{s} {} ~TimerCircle() { if (thread_.joinable()) { terminate(); thread_.join(); } } TimerCircle(const TimerCircle&) = delete; TimerCircle& operator=(const TimerCircle&) = delete; TimerCircle(TimerCircle&&) = default; TimerCircle& operator=(TimerCircle&&) = default; public: void launch() { thread_ = std::move(std::thread(&TimerCircle::loop, this)); } void terminate() { cv_.terminate(); } void loop() { while (cv_.wait_for(std::chrono::seconds(sleep_))) { do_something(); } } private: void do_something() const = 0; };
簡(jiǎn)單,明了。
總結(jié)
到此這篇關(guān)于如何在C++中實(shí)現(xiàn)一個(gè)正確的時(shí)間循環(huán)器的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)時(shí)間循環(huán)器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c++標(biāo)準(zhǔn)輸入輸出流關(guān)系的前世今生
這篇文章主要給大家介紹了關(guān)于c++標(biāo)準(zhǔn)輸入輸出流關(guān)系的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04C++實(shí)現(xiàn)希爾排序(ShellSort)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)希爾排序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04詳解C語(yǔ)言求兩個(gè)數(shù)的最大公約數(shù)及最小公倍數(shù)的方法
這篇文章主要介紹了C語(yǔ)言求兩個(gè)數(shù)的最大公約數(shù)及最小公倍數(shù)的方法,輾轉(zhuǎn)相除法和輾轉(zhuǎn)相減法在解決這種問(wèn)題時(shí)最常用到,需要的朋友可以參考下2016-03-03C語(yǔ)言算法的時(shí)間復(fù)雜度和空間復(fù)雜度
這篇文章主要介紹了C語(yǔ)言算法的時(shí)間復(fù)雜度和空間復(fù)雜度,算法在編寫(xiě)成可執(zhí)行程序后,運(yùn)行時(shí)需要耗費(fèi)時(shí)間資源和空間(內(nèi)存)資源,更多相關(guān)需要的朋友可以參考一下2022-07-07C/C++ break和continue區(qū)別及使用方法
這篇文章主要介紹了C/C++ break和continue區(qū)別及使用方法的相關(guān)資料,需要的朋友可以參考下2017-07-07c++函數(shù)中的指針參數(shù)與地址參數(shù)區(qū)別介紹
c++函數(shù)中的指針參數(shù)與地址參數(shù)區(qū)別介紹;可供參考2012-11-11獲取C語(yǔ)言中int類(lèi)型的最大值的方法小結(jié)
在C語(yǔ)言中,int?類(lèi)型的大小通常是根據(jù)系統(tǒng)架構(gòu)來(lái)決定的,在大多數(shù)現(xiàn)代系統(tǒng)上,int?通常是32位的,在C語(yǔ)言中,獲取int類(lèi)型的最大值有幾種不同的方法,下面,我們將討論兩種方法:使用標(biāo)準(zhǔn)庫(kù)函數(shù)和使用算法,需要的朋友可以參考下2024-06-06基于C語(yǔ)言實(shí)現(xiàn)計(jì)算生辰八字五行的示例詳解
生辰八字,簡(jiǎn)稱(chēng)八字,是指一個(gè)人出生時(shí)的干支歷日期;年月日時(shí)共四柱干支,每柱兩字,合共八個(gè)字。這篇文章主要介紹了C語(yǔ)言實(shí)現(xiàn)計(jì)算生辰八字五行的示例代碼,需要的可以參考一下2023-03-03淺談C++中對(duì)象的復(fù)制與對(duì)象之間的相互賦值
這篇文章主要介紹了淺談C++中對(duì)象的復(fù)制與對(duì)象之間的相互賦值,是C語(yǔ)言入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09