2

I've got a boost::asio based thread pool running on N threads. It used mainly for IO tasks (DB data storing/retreival). It also launches self-diagnostic timer job to check how 'busy' pool is (calculates ms diff between 'time added' and 'time handler called') So the question is - is there any way to stop M of N threads ( for cases when load is very low and pool does not need so many threads). When the load is high (determined by diagnostic task) then new thread is added:

_workers.emplace_back(srv::unique_ptr<srv::thread>(new srv::thread([this]
{
    _service.run();
})));

(srv namespace is used to switch quickly between boost and std) But when 'peak load' is passed I need some way to stop additional threads. Is there any solution for this?

4

1 回答 1

1

您正在寻找的是一种中断正在等待的线程的方法io_service。您可以使用异常来实现某种中断机制。

class worker_interrupted : public std::runtime_error
{
public:
    worker_interrupted() 
    : runtime_error("thread interrupted") {}
};


_workers.emplace_back(srv::unique_ptr<srv::thread>(new srv::thread([this]
{
    try
    {
        _service.run();
    }
    catch (const worker_interrupted& intrruption)
    {
        // thread function exits gracefully.
    }

})));

然后,您可以使用io_service::post将仅引发worker_interrupted异常的完成处理程序加入队列。

于 2018-05-14T20:00:18.767 回答