From cf6168a89a784521df0c9d63a049bc025daa1b85 Mon Sep 17 00:00:00 2001 From: taynpg Date: Wed, 18 Dec 2024 13:55:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=AF=E4=B8=AD=E6=AD=A2sl?= =?UTF-8?q?eep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/of_util.h | 21 +++++++++++++++++++++ src/of_util.cpp | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/include/of_util.h b/include/of_util.h index bbac325..c7f454a 100644 --- a/include/of_util.h +++ b/include/of_util.h @@ -246,4 +246,25 @@ public: #endif }; +typedef class CThreadSleep +{ +public: + CThreadSleep(); + ~CThreadSleep() = default; + +public: + void sleep(int milsec = 0); + void contiune(); + void set_timeout(int milsec); + +private: + bool get_status() const; + +private: + std::condition_variable cv_; + int timeout_; + const int default_timeout_ = 10; + std::mutex mutex_; + bool is_stop_sleep_; +} ThreadSleep; } // namespace ofen diff --git a/src/of_util.cpp b/src/of_util.cpp index ea3bbf8..055bac2 100644 --- a/src/of_util.cpp +++ b/src/of_util.cpp @@ -114,4 +114,40 @@ std::string CCodec::GBKTou8(const std::string& str) return utf8Str; } #endif +CThreadSleep::CThreadSleep() +{ + is_stop_sleep_ = false; + timeout_ = 10; +} +void CThreadSleep::sleep(int milsec) +{ + int sleep_time = timeout_; + if (milsec > 0) + sleep_time = milsec; + + is_stop_sleep_ = false; + std::unique_lock lock(mutex_); + std::chrono::system_clock::time_point nowtime = std::chrono::system_clock::now(); + if (cv_.wait_until(lock, nowtime + (std::chrono::milliseconds(sleep_time)), [this] { return get_status(); })) { + // 手动 + } else { + // 超时 + } +} +void CThreadSleep::contiune() +{ + is_stop_sleep_ = true; + cv_.notify_all(); +} +void CThreadSleep::set_timeout(int milsec) +{ + if (milsec <= 0) + timeout_ = default_timeout_; + else + timeout_ = milsec; +} +bool CThreadSleep::get_status() const +{ + return is_stop_sleep_; +} } // namespace ofen