| 565 | } |
| 566 | |
| 567 | Status ThreadPool::SetCapacity(int threads) { |
| 568 | std::unique_lock<std::mutex> lock(state_->mutex_); |
| 569 | if (state_->please_shutdown_) { |
| 570 | return Status::Invalid("operation forbidden during or after shutdown"); |
| 571 | } |
| 572 | if (threads <= 0) { |
| 573 | return Status::Invalid("ThreadPool capacity must be > 0"); |
| 574 | } |
| 575 | CollectFinishedWorkersUnlocked(); |
| 576 | |
| 577 | state_->desired_capacity_ = threads; |
| 578 | // See if we need to increase or decrease the number of running threads |
| 579 | const int required = std::min(static_cast<int>(state_->pending_tasks_.size()), |
| 580 | threads - static_cast<int>(state_->workers_.size())); |
| 581 | if (required > 0) { |
| 582 | // Some tasks are pending, spawn the number of needed threads immediately |
| 583 | LaunchWorkersUnlocked(required); |
| 584 | } else if (required < 0) { |
| 585 | // Excess threads are running, wake them so that they stop |
| 586 | state_->cv_.notify_all(); |
| 587 | } |
| 588 | return Status::OK(); |
| 589 | } |
| 590 | |
| 591 | int ThreadPool::GetCapacity() { |
| 592 | std::unique_lock<std::mutex> lock(state_->mutex_); |