使用條件變數condition_variable實現超時功能
阿新 • • 發佈:2022-03-08
#include <iostream> #include <thread> #include <condition_variable> #include <mutex> #include <chrono> class TestTimeout { public : TestTimeout() { timeout_ms_ = 1000; /// default flag = false; } ~TestTimeout(){} void Test(int timeout_ms) { timeout_ms_= timeout_ms; flag = false; std::thread t1 = std::thread(&TestTimeout::RunFunc, this); std::thread t2 = std::thread(&TestTimeout::WaitTimeoutFunc, this); t1.join(); t2.join(); } private: void RunFunc() { std::unique_lock<std::mutex> lck(mtx); /// do something std::this_thread::sleep_for(std::chrono::seconds(1)); cv.notify_one(); } void WaitTimeoutFunc(){ while(1) { std::unique_lock<std::mutex> lck(mtx); if (cv.wait_until(lck, std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms_), [&](){returnflag == true;})) { return; } } } private: int timeout_ms_; std::condition_variable cv; std::mutex mtx; bool flag; }; int main() { TestTimeout* test = new TestTimeout; test->Test(100); return 0; }