Run a single thread.
| 58 | |
| 59 | // Run a single thread. |
| 60 | void ThreadPool::run() { |
| 61 | while (true) { |
| 62 | std::unique_lock<std::mutex> lock(this->tasks_mutex_); |
| 63 | while (!this->stop_ && this->tasks_.empty()) { |
| 64 | this->tasks_condition_.wait(lock); |
| 65 | } |
| 66 | if (this->stop_ && this->tasks_.empty()) { |
| 67 | return; |
| 68 | } |
| 69 | std::function<void()> task(this->tasks_.front()); |
| 70 | this->tasks_.pop(); |
| 71 | ++active_threads_; |
| 72 | // Unlock the queue while we execute the task. |
| 73 | lock.unlock(); |
| 74 | task(); |
| 75 | lock.lock(); |
| 76 | --active_threads_; |
| 77 | // This is the secret to making the waitForEmptyQueue() function work. |
| 78 | // After finishing a task, notify that this work is done. |
| 79 | wait_condition_.notify_all(); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // This method blocks until the queue is empty. |
| 84 | void ThreadPool::waitForEmptyQueue() const { |