2014-03-26 243 views
1

在我的多线程程序中,我经常使用如下所示的方法来同步访问数据:等待异步方法来完成

class MyAsyncClass 
{ 

public:  // public thread safe interface of MyAsyncClass 

    void start() 
    { 
     // add work to io_service 
     _ioServiceWork.reset(new boost::asio::io_service::work(_ioService)); 

     // start io service 
     _ioServiceThread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&boost::asio::io_service::run, &_ioService))); 
    } 

    void stop() 
    { 
     _ioService.post(boost::bind(&MyAsyncClass::stop_internal, this)); 

     // QUESTION: 
     // how do I wait for stop_internal to finish here? 

     // remove work 
     _ioServiceWork.reset(); 

     // wait for the io_service to return from run() 
     if (_ioServiceThread && _ioServiceThread->joinable()) 
      _ioServiceThread->join(); 

     // allow subsequent calls to run() 
     _ioService.reset(); 

     // delete thread 
     _ioServiceThread.reset(); 
    } 

    void doSometing() 
    { 
     _ioService.post(boost::bind(&MyAsyncClass::doSometing_internal, this)); 
    } 

private:  // internal handlers 

    void stop_internal() 
    { 
     _myMember = 0; 
    } 

    void doSomething_internal() 
    { 
     _myMember++; 
    } 

private:  // private variables 

    // io service and its thread 
    boost::asio::io_service _ioService; 
    boost::shared_ptr<boost::thread> _ioServiceThread; 

    // work object to prevent io service from running out of work 
    std::unique_ptr<boost::asio::io_service::work> _ioServiceWork; 

    // some member that should be modified only from _ioServiceThread 
    int _myMember; 

}; 

这个类的公共接口是线程安全的意义它的公共方法可以从任何线程调用,并且boost::asio::io_service注意同步对此类的私有成员的访问。因此,公众doSomething()除了将实际工作发布到io_service之外不做任何事情。

start()stop()方法MyAsyncClass明显在MyAsyncClass开始和停止处理。我希望能够从任何线程调用MyAsyncClass::stop(),并且在MyAsyncClass的未初始化完成之前它不应该返回。

因为在这种特殊情况下,我需要在停止时修改其中一个私人成员(需要同步访问),我引入了一个stop_internal()方法,我从stop()发布到io_service

现在的问题是:我如何等待执行stop_internal()完成stop()?请注意,我不能直接调用stop_internal(),因为它会在错误的线程中运行。

编辑:

这将是很好有一个解决方案,同时工作,如果MyAsyncClass::stop()_ioServiceThread叫,让MyAsyncClass也可自行停止。

回答

1

我只是找到了一个非常好的解决自己:

除删除工作在stop()(重置_ioServiceWork),我做这件事的stop_internal()结束。这意味着_ioServiceThread->join()阻止,直到stop_internal()完成 - 正是我想要的。

这个解决方案的好处是它不需要任何互斥或条件变量或类似的东西。