• boost::asio timer用法总结


    代码:(lambda表达式实现和bind实现)

    #include <iostream>
    #include <boost/bind.hpp>
    #include <boost/asio.hpp>
    #include <boost/thread.hpp>
    #include <chrono>
    
    namespace io = boost::asio;
    
    io::io_context io_context_;
    io::high_resolution_timer timer(io_context_, std::chrono::microseconds(0));
    int timerinterval = 1000000;
    std::thread _thread;
    
    auto now() {
        return std::chrono::high_resolution_clock::now();
    }
    auto begin_timepoint = now();
    
    void async_wait() {
        timer.expires_at(timer.expires_at() + std::chrono::microseconds(timerinterval));
        timer.async_wait([&](boost::system::error_code error) {
            auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(now() - begin_timepoint).count();
            std::cout << "elapsed: " << elapsed << std::endl;
            begin_timepoint = now();
            async_wait();
        });
    }
    
    void async_wait_bind(const boost::system::error_code& e) {
        if (!e) {
            std::cout << "handle handle" << std::endl;
        }
        timer.expires_at(timer.expires_at() + std::chrono::microseconds(timerinterval));
        timer.async_wait(boost::bind(&async_wait_bind, boost::asio::placeholders::error));
    }
    
    
    int main()
    {
        while (1) {
            int key = _getch();
            //ESC
            if (key == 27) {
                timer.cancel();
                io_context_.stop();
                _thread.join();
                break;
            }//s timer lambda practice
            if (key == 115) {
                async_wait();
                _thread = std::thread([] {io_context_.run(); });
            }
            //u timer bind practice
            if (key == 117) {
                timer.expires_at(timer.expires_at() + std::chrono::microseconds(timerinterval));
                timer.async_wait(boost::bind(&async_wait_bind, boost::asio::placeholders::error));
                _thread = std::thread([] {io_context_.run(); });
            }
        }
    }
  • 相关阅读:
    牛客网-2019校招真题-跳格子游戏(斐波那契数列)
    牛客网-2019校招真题-学数学
    牛客网-2019校招真题-方格走法
    牛客网-2019年校招真题-通过率降序(二)
    牛客网-2019年校招真题-通过率降序(一)
    常用数据库连接URL的举例
    Css3-渐变
    清除浮动的方法
    html中的条件注释
    Css中的定位
  • 原文地址:https://www.cnblogs.com/foreversdf/p/12974873.html
Copyright © 2020-2023  润新知