2013-07-18 77 views
0

感谢您回复Sam Miller,但我需要在Windows上实现它。如何在1个线程上运行boost :: asio :: io_service唤醒等待条件

请看下面的例子Ø写道:

boost::mutex mut; 
boost::condition_variable cond; 

boost::asio::io_service io_service; 

boost::asio::deadline_timer t(io_service); 

void test_func() 
{ 
    boost::mutex::scoped_lock lk(mut); 
    cond.notify_all(); 
} 

void cancel_test_func() 
{ 
    boost::unique_lock<boost::mutex> lk(mut); 
    auto canceled_timers = t.cancel(); 
    cond.wait(lk); 
    printf("Canceled...%u.", canceled_timers); 
} 

int main(int argc, char* argv[]) 
{ 
    try 
    { 
    t.expires_from_now(boost::posix_time::seconds(5)); 
    t.async_wait(boost::bind(&test_func)); 

    io_service.post(boost::bind(cancel_test_func)); 

    boost::thread_group tg; 
    tg.create_thread(boost::bind(&boost::asio::io_service::run, &io_service)); 
    //tg.create_thread(boost::bind(&boost::asio::io_service::run, &io_service)); 

    getchar(); 
    } 
    catch (std::exception& e) 
    { 
    std::cerr << "Exception: " << e.what() << "\n"; 
    } 

    return 0; 
} 

为了使这个例子工程(取消计时器)我需要取消对第二个线程的创建。只有一个线程,我从来没有收到通知。 现在的问题是:这种行为是否正常?

+0

'cond.wait'解锁互斥锁,'io_service'线程由于'timer.cancel()'而进入'timeout_func',并通知'cond'在“主”线程中等待 - 没有无限的等待。 –

+0

但是,同一个线程怎么会进入'timeout_func'并等待条件呢?要进入'timeout_func',它应该中断等待,转到回调,调用'notify_one'然后回到条件的'wait' –

+0

它不是一样的线程,它们是两个不同的线程:线程A设置定时器,创建线程B并传递给它'io_service :: run'函数,然后立即取消定时器,并等待'cond'。由于定时器取消,线程B调用完成处理程序,即进入'timeout_function',并通知'cond'。 –

回答

0

条件变量是一个同步的概念,它不能很好地与事件循环相结合,如io_service。如果您想在Linux上进行异步事件,请查看eventfd(2)以及信号量语义的EFD_SEMAPHORE标志。我不确定在其他平台上是否有类似的接口

相关问题