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