ThreadPool with boost :: asio not going away?

I have the following example of a minmal thread pool created with boost :: asio.

#include <queue>
#include <map>

#include <boost/shared_ptr.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp> // remove me (only for io)

class ThreadPool
{
public:
    void work_as_mainthread(void) { m_io_service.run(); }

    ThreadPool(int poolSize = 4) : timer(m_io_service)
    {
        timer.expires_from_now(boost::posix_time::seconds(1)); // this line does not affect the problem
        m_pWork.reset( new boost::asio::io_service::work(m_io_service) );

        for ( int i = 0; i < poolSize; ++i)
            m_threadGroup.create_thread( boost::bind(&boost::asio::io_service::run, &m_io_service) );
    }

    ~ThreadPool()
    {
        m_pWork.reset();
        m_threadGroup.join_all();
    }

private:
    boost::asio::io_service m_io_service;
    boost::asio::deadline_timer timer;
    boost::shared_ptr<boost::asio::io_service::work> m_pWork;
    boost::thread_group m_threadGroup;
};

int main()
{
    int n_threads = 2;
    ThreadPool pool(n_threads);
    pool.work_as_mainthread();
    // this line is never reached...
    return 0;
}

      

If you like, you can compile it like this:

g++ -Wall -g -lboost_thread -lboost_date_time -lboost_system main.cpp -o main

      

Which makes me wonder if the program doesn't stop. I am making a call to io_service :: run, but without any "work" for it. The io_services go out of their way without work as said in the boost :: asio docs. Now why does my program never end?

0


source to share


1 answer


When you create an object boost::asio::io_service::work

that doesn't execute io_service

.

// This line keeps the io_service running
m_pWork.reset( new boost::asio::io_service::work(m_io_service) );

      

If you want it to stop, you will need to destroy that work object, for example:



// stop the worker(s)
m_pWork.reset();

      

You need to find the right time / place for this. I would suggest calling timer.async_wait()

and then in the handler you can reset your work object to see how it all should work together.

See this part of the documentation.

+3


source







All Articles