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(); });
            }
        }
    }
  • 相关阅读:
    个人技术总结——Flask-Admin扩展
    个人作业——软件工程实践总结&个人技术博客
    个人作业——软件评测
    结对第二次作业——某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
    软工实践寒假作业(2/2)
    软工实践寒假作业(1/2)
    计算与软件工程 作业五
    计算与软件工程 作业四
    计算与软件工程 作业三
  • 原文地址:https://www.cnblogs.com/foreversdf/p/12974873.html
Copyright © 2011-2022 走看看