MRPT  1.9.9
WorkerThreadsPool.cpp
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | https://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file |
6  | See: https://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See: https://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 
10 #include "system-precomp.h" // Precompiled header
11 
12 #include <mrpt/core/exceptions.h>
14 #include <iostream>
15 
16 using namespace mrpt::system;
17 
19 {
20  {
21  std::unique_lock<std::mutex> lock(queue_mutex_);
22  do_stop_ = true;
23  }
24  condition_.notify_all();
25 
26  if (!tasks_.empty())
27  std::cerr << "[threadPool] Warning: clear() called (probably from a "
28  "dtor) while having "
29  << tasks_.size() << " pending tasks. Aborting them.\n";
30 
31  for (auto& t : threads_)
32  if (t.joinable()) t.join();
33  threads_.clear();
34 }
35 
36 std::size_t WorkerThreadsPool::pendingTasks() const noexcept
37 {
38  return tasks_.size();
39 }
40 
41 void WorkerThreadsPool::resize(std::size_t num_threads)
42 {
43  for (std::size_t i = 0; i < num_threads; ++i)
44  threads_.emplace_back([this] {
45  for (;;)
46  {
47  try
48  {
49  std::function<void()> task;
50  {
51  std::unique_lock<std::mutex> lock(queue_mutex_);
52  condition_.wait(lock, [this] {
53  return do_stop_ || !tasks_.empty();
54  });
55  if (do_stop_) return;
56  task = std::move(tasks_.front());
57  tasks_.pop();
58  }
59  // Execute:
60  task();
61  }
62  catch (std::exception& e)
63  {
64  std::cerr << "[thread-pool] Exception:\n"
65  << mrpt::exception_to_str(e) << "\n";
66  }
67  }
68  });
69 }
std::condition_variable condition_
std::vector< std::thread > threads_
std::queue< std::function< void()> > tasks_
void resize(std::size_t num_threads)
void clear()
Stops all working jobs.
std::size_t pendingTasks() const noexcept
Returns the number of enqueued tasks, currently waiting for a free working thread to process them...



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: c7a3bec24 Sun Mar 29 18:33:13 2020 +0200 at dom mar 29 18:50:38 CEST 2020