Boost/C++实现中如何控制线程池

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

我正在开发一个非常基本的应用程序,以自学线程池并能够使用 boost 在 C++ 中控制它们。

我想要做的是能够发出一个命令,该命令可以 pause/restart 正在使用的线程池之一。

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;
}

对 io_service.stop 的调用实际上并未停止线程池中的任何线程。

问题,为什么线程不停止,是因为当你停止时 io_service,它实际上会尽快停止执行事件循环。但是当前事件是无限循环的。我认为您应该使用 atomic_bool 来设置某种 "stopping" 状态并在线程内检查此状态。

顺便说一句,你应该在 stop()run() 之间使用 io_service.reset()