Search code examples
c++multithreadingboostthreadpool

How to Control Thread Pool in Boost/C++ Implementation


I'm working on a really basic application to teach myself about thread pools and being able to control them in c++ using boost.

What I'm trying to do is to be able to issue a command that can pause/restart one of the thread pools that are being used.

void printStuff(int x){

    while(true){    
        std::cout <<" Hi from thread 1 in group " << x << std::endl;        
        boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
     }
}

void pstwo(int x){
    while(true){    
        std::cout <<" Hi from thread 2 in group " << x << std::endl;    
        boost::this_thread::sleep( boost::posix_time::milliseconds(1500) );
     }
 }

int main()
{
    boost::asio::io_service io_service;

    boost::asio::io_service::work work(io_service);

    boost::asio::io_service io_service2;

    boost::asio::io_service::work work2(io_service2);

    boost::thread_group threads;
    boost::thread_group threadsTwo;
    for (std::size_t i = 0; i < 2; ++i)
      threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));

    for (std::size_t i = 0; i < 2; ++i)
      threadsTwo.create_thread(boost::bind(&boost::asio::io_service::run, &io_service2));

    io_service.post(boost::bind(printStuff,1));
    io_service.post(boost::bind(pstwo,1));

    io_service2.post(boost::bind(printStuff,2));
    io_service2.post(boost::bind(pstwo,2));

    boost::this_thread::sleep( boost::posix_time::milliseconds(10000));
    io_service.stop();
    std::cout<<"------------------"<<std::endl;
    boost::this_thread::sleep( boost::posix_time::milliseconds(10000));
    io_service.run();    
    io_service2.stop();
    std::cout<<"-----------------"<<std::endl;
    boost::this_thread::sleep( boost::posix_time::milliseconds(10000));
    io_service.stop();
    threads.join_all();
    threadsTwo.join_all();
    return 0;
}

The calls to io_service.stop do not actually stop any of the threads in the thread pool.


Solution

  • The problem, why the threads don't stop, is because when you stop io_service, it actually stops executing the event loop as soon as it is possible. But the current event is infinite loop. I think you should use for example atomic_bool to set some kind of "stopping" state and to check this state inside the threads.

    By the way, you should use io_service.reset() between stop() and run().