thread-pool icon indicating copy to clipboard operation
thread-pool copied to clipboard

fixup bug as description in #39

Open muyuuuu opened this issue 3 years ago • 0 comments

I found that m_queue.size() isn't equal to zero when pool.shutdown() was runned, so some tasks do not finish when the thread pool closes.

I fixed it up as follows:

void operator()() {
  std::function<void()> func;
  bool dequeued;
  while (!m_pool->m_shutdown) {
    {
      std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);
      if (m_pool->m_queue.empty()) {
        m_pool->m_conditional_lock.wait(lock);
      }
      dequeued = m_pool->m_queue.dequeue(func);
    }
    if (dequeued) {
      func();
    }
  }

  // If the task queue is not empty, continue obtain task from task queue, 
  // the multithread continues execution until the queue is empty
  while (!m_pool->m_queue.empty()) {
    {
      std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);
      dequeued = m_pool->m_queue.dequeue(func);
      if (dequeued) {
        func();
      }
    }
  }
}

muyuuuu avatar Aug 14 '21 03:08 muyuuuu