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