zoukankan      html  css  js  c++  java
  • 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(); });
            }
        }
    }
  • 相关阅读:
    《世界是数字的》
    IT小小鸟读书笔记
    Codeforces Round #665 Div.2 (CF1401)
    Codeforces Round #662 Div.2 (CF1392)
    std::array的效率问题
    CSS布局学习总结
    TCP中三次握手与四次挥手
    初见Vuex
    初见webpack
    CentOS7使用yum简便安装mysql5.7
  • 原文地址:https://www.cnblogs.com/foreversdf/p/12974873.html
Copyright © 2011-2022 走看看