我有一个调度程序类(下面的剥离实现),它创建一个I / O服务并允许启动工作线程执行io_service处理程序。在我告诉它们停止之前,这些线程应保持 Activity 状态。为此,我使用了io_service::work对象。但是,尽管存在工作对象,但这些线程不会保持 Activity 状态。关于如何正确使用io_service::work的任何想法吗?

这是一个显示问题的最小工作示例(在下面提供了DispatcherClass):

#include <boost/asio.hpp>
#include <boost/thread.hpp>

void myDispatcherMainThread(DispatcherClass &dispatcher)
{
    std::cout << "Dispatcher Started\n";
    dispatcher.AddCtrlCHandling();
    if (dispatcher.Run(2))
        std::cout << "Dispatcher is about to finish (expected).\n";
    else
        std::cout << "Dispatcher is about to finish (unexpected).\n";
}


int main(int argc, char* argv[]) {
    DispatcherClass dispatcher;
    boost::thread maindispatcherthread(myDispatcherMainThread,boost::ref(dispatcher));
    boost::this_thread::sleep(boost::posix_time::seconds(5));
    if (dispatcher.get_io_service().stopped())
        std::cout << "Dispatcher should not have finished!";

    dispatcher.cleanStop();
    maindispatcherthread.join();
}

这是调度程序类(在此处使此帖子可读):
class DispatcherClass : private boost::noncopyable {
public:
    DispatcherClass():
      _ioService(),
      _pKeepWorking(new boost::asio::io_service::work( _ioService )),
      _expectingdispatchend(false){}

    boost::asio::io_service &get_io_service() { return _ioService; }

    // Start the dispatcher threads
    bool Run(unsigned int numThreads = -1)
    {
        // Recover after a clean stop
        if (!_pKeepWorking)
            _pKeepWorking.reset(new boost::asio::io_service::work( _ioService ));

        // Reset after clean or forced stop
        if (_ioService.stopped())
        {
            _expectingdispatchend = false;
            _ioService.reset();
        }

        // Start message dispatch threads
        boost::thread_group workerThreads;
        for (unsigned int i = 0; i < ((numThreads == (unsigned int)-1) ? (boost::thread::hardware_concurrency()) : numThreads); ++i)
            workerThreads.create_thread(boost::bind(&DispatcherClass::WorkerThread, this));

        // Wait until all threads finish
        workerThreads.join_all();

        return _expectingdispatchend;
    }

    // Stop the dispatcher threads
    void Stop()
    {
        _expectingdispatchend = true;
        _ioService.stop();
    }

    void cleanStop()
    {
        _expectingdispatchend = true;
        _pKeepWorking.reset();
    }

    // Stop the dispatcher threads on CTRL-C
    void AddCtrlCHandling()
    {
        boost::asio::signal_set sig_set(_ioService, SIGTERM, SIGINT);
        sig_set.async_wait(boost::bind(&boost::asio::io_service::stop, boost::ref(_ioService)));
    }

private:
    bool _expectingdispatchend;

    boost::asio::io_service _ioService;
    boost::shared_ptr< boost::asio::io_service::work > _pKeepWorking;

    void WorkerThread()
    {
        while (true) {
        try
        {
            boost::system::error_code ec;
            _ioService.run(ec);
            break;
        }
        catch (const std::exception &) {}
        }
    }
};

最佳答案

在已取消的io_service::stop()中调用 SignalHandler ,导致io_service::run()的所有调用尽快返回。

void DispatcherClass::AddCtrlCHandling()
{
    boost::asio::signal_set sig_set(...);
    sig_set.async_wait(boost::bind(
        &boost::asio::io_service::stop, boost::ref(_ioService)));
}

DispatcherClass::AddCtrlCHandling()中,sig_set是类型为 boost::asio::signal_set 的自动变量,函数返回后其生命周期结束。在signal_set析构函数中,对signal_set的所有未完成的异步等待操作都将以boost::asio::error::operation_aborted的错误代码完成。因此,将调用SignalHandlerio_service::stop()排队到io_service中,并由工作线程之一调用。要解决此问题,请考虑通过使signal_set成为sig_set的成员变量来延长DispatcherClass的寿命。

关于c++ - 尽管有工作对象,asio::io_service.run()仍会退出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20888301/

10-17 02:14