同步怎么处理某一操作超时问题

在项目中遇到同步处理某一操作比较耗时,不想让用户等太长时间,所以想强制推出该操作。

例子:

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>  
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;  
using boost::asio::ip::tcp;
using boost::asio::ip::address;

void Print()
{
    boost::asio::io_service io;
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
    t.wait();

    cout<<"Hello World!"<<endl;
    cout<<boost::this_thread::get_id()<<endl;
}
int main()
{  
    boost::asio::io_service io;
    boost::thread thr1(Print);
    tcp::socket msocket(io);
    tcp::endpoint m_endpoint;
    boost::asio::ip::address addr = boost::asio::ip::address::from_string("127.0.0.1");
    
    m_endpoint = boost::asio::ip::tcp::endpoint(addr, 2000);  //无法连接
    try
    {
         msocket.connect(m_endpoint);
    }
    catch (const std::exception& e)
    {
        cout<<e.what()<<endl;
    }
    thr1.join();
    cout<<"connect"<<endl;
    system("PAUSE");
    return 0;
}

  输出结果:

 

posted @ 2018-09-14 18:13  木木ing  阅读(505)  评论(0编辑  收藏  举报