boost::asio::steady_timer的一个错误用法

来源:互联网 发布:粤贵银模拟交易软件 编辑:程序博客网 时间:2024/05/03 20:11

boost::asio::steady_timer的一个错误用法。

//使用boost.chrono代替std.chrono,#define BOOST_ASIO_DISABLE_STD_CHRONO#include <boost/asio.hpp>#include <boost/asio/steady_timer.hpp>#include <boost/asio/placeholders.hpp>#include <boost/thread.hpp>#include <boost/format.hpp>bool g_isExit = false;void DoSth(int idx, const boost::system::error_code& errCode){    if (errCode)    {        std::string str = (boost::format("idx=%|d|, value=%|d|, message=%|s|") % idx%errCode.value() % errCode.message()).str();        std::cout << str << std::endl;        return;    }    else    {        std::string str = (boost::format("idx=%|d|, doing") % idx).str();        std::cout << str << std::endl;    }    boost::this_thread::sleep_for(boost::chrono::seconds(3));//做什么事情,花费了3秒钟,    g_isExit = true;    return;}int main(int argc, char** argv){    boost::thread_group thgp;    boost::asio::io_service io;    boost::asio::io_service::work wk(io);    thgp.create_thread(boost::bind(&boost::asio::io_service::run, boost::ref(io)));    thgp.create_thread(boost::bind(&boost::asio::io_service::run, boost::ref(io)));    boost::asio::steady_timer timer(io);    //boost::asio::steady_timer注册了一个回调函数,这个回调函数将在1000ms后被回调,    timer.expires_from_now(boost::chrono::milliseconds(1000));    timer.async_wait(boost::bind(&DoSth, 1, boost::asio::placeholders::error));    //回调函数没有被处理之前,又注册了一个回调函数,那么上一个回调函数就会执行失败,    //错误信息: value=995, message=由于线程退出或应用程序请求,已中止 I/O 操作。    timer.expires_from_now(boost::chrono::milliseconds(1000));    timer.async_wait(boost::bind(&DoSth, 2, boost::asio::placeholders::error));    while (false == g_isExit)    {        boost::this_thread::sleep_for(boost::chrono::milliseconds(10));    }    std::cout << "press ENTER to exit..." << std::endl;    std::cin.sync();    while (getchar() != '\n') {}}

完。

0 0
原创粉丝点击