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(); });
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/foreversdf/p/12974873.html