刘总的笔记小站

生活常识,娱乐搞笑,编程技巧,智能家居,深度学习,网络神经,数据挖掘

c++ std::condition_variable Predicate Only visit two times...

代码逻辑实现如下:

    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



发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
搜索
«   2024年9月   »
1
2345678
9101112131415
16171819202122
23242526272829
30
网站分类
最新留言
文章归档
网站收藏
友情链接
图标汇集
Powered by Z-BlogPHP

  • Copyright ©2021 @liuzong All rights reserved.
  • 陕ICP备17016542号