2
votes

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?

1

1 Answers

1
votes

What you are looking for is a way to interrupt a thread that is waiting on the io_service. You can implement some sort of interruption mechanism using exceptions.

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

})));

You could then just use io_service::post to enqueue a completion handler which just throws worker_interrupted exception.