代码逻辑实现如下:
try { using string = std::string; static const string str("I like to code in C c++ python go"); util::Config &config = util::Config::GetInstance(); // initial util::Logger &logger = util::Logger::GetInstance(); // initial auto now = std::chrono::steady_clock::now(); std::atomic<bool> ready(false); // std::atomic_bool is_running(false); std::mutex mutx; // mutable std::unique_lock<std::mutex> lock(mutx); std::condition_variable cond; // Predicate pred Only visit start and end... std::thread thrd([&](){ logger.debug("thread sleep:{}s", std::chrono::duration<float>(std::chrono::steady_clock::now() - now).count()); std::this_thread::sleep_for(std::chrono::seconds(1)); ready = true; cond.notify_one(); logger.debug("thread notify:{}s", std::chrono::duration<float>(std::chrono::steady_clock::now() - now).count()); }); if (cond.wait_for(lock, std::chrono::milliseconds(3 * 1000), [&]() { logger.debug("proccess precode:{}s", std::chrono::duration<float>(std::chrono::steady_clock::now() - now).count()); return (ready == true); })) { logger.debug("proccess wait_for:{}s", std::chrono::duration<float>(std::chrono::steady_clock::now() - now).count()); } else { logger.debug("proccess timeout:{}s", std::chrono::duration<float>(std::chrono::steady_clock::now() - now).count()); } thrd.join(); // proccess precode:0.0004306s // thread sleep:0.0004152s // thread notify:1.0143577s // proccess precode:1.0143545s // proccess wait_for:1.0186943s } catch (std::exception &error) { std::cout << "exception error:" << error.what() << " @" << __FILE__ << __LINE__ << std::endl; }
运行时序流程参见日志:
2023-08-03 09:57:05.713 [logger][debug][2632][4548]:config.con_file:D:\code\template\build\Debug\conf\template.json 2023-08-03 09:57:05.714 [logger][debug][2632][4548]:logger.log_file:D:\code\template\build\Debug\logs\template.log 2023-08-03 09:57:05.714 [logger][debug][2632][4548]:proccess precode:0.0004306s 2023-08-03 09:57:05.714 [logger][debug][2632][2508]:thread sleep:0.0004152s 2023-08-03 09:57:06.728 [logger][debug][2632][2508]:thread notify:1.0143577s 2023-08-03 09:57:06.728 [logger][debug][2632][4548]:proccess precode:1.0143545s 2023-08-03 09:57:06.733 [logger][debug][2632][4548]:proccess wait_for:1.0186943s