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