fw4spl
Pool.cpp
1 /* ***** BEGIN LICENSE BLOCK *****
2  * FW4SPL - Copyright (C) IRCAD, 2015-2018.
3  * Distributed under the terms of the GNU Lesser General Public License (LGPL) as
4  * published by the Free Software Foundation.
5  * ****** END LICENSE BLOCK ****** */
6 
7 #include "fwThread/Pool.hpp"
8 
9 #include <fwCore/spyLog.hpp>
10 #include <fwCore/util/LazyInstantiator.hpp>
11 
12 namespace fwThread
13 {
14 
15 //-----------------------------------------------------------------------------
16 
18  Pool(std::thread::hardware_concurrency())
19 {
20 }
21 
22 //-----------------------------------------------------------------------------
23 
24 Pool::Pool(size_t _threads) :
25  m_stop(false)
26 {
27  const auto availableCores = std::thread::hardware_concurrency();
28  OSLM_WARN_IF( _threads << " threads were allocated in this thread pool, but you only have " <<
29  availableCores << " physical cores on this CPU",
30  _threads > std::thread::hardware_concurrency());
31 
32  for(size_t i = 0; i < _threads; ++i)
33  {
34  m_workers.emplace_back(
35  [this]
36  {
37  for(;; )
38  {
39  std::function<void()> task;
40 
41  {
42  std::unique_lock<std::mutex> lock(m_queueMutex);
43  m_condition.wait(lock, [this] { return m_stop || !m_tasks.empty(); });
44  if(m_stop && m_tasks.empty())
45  {
46  return;
47  }
48  task = std::move(m_tasks.front());
49  m_tasks.pop();
50  }
51 
52  task();
53  }
54  }
55  );
56  }
57 }
58 
59 //-----------------------------------------------------------------------------
60 
62 {
63  {
64  std::unique_lock<std::mutex> lock(m_queueMutex);
65  m_stop = true;
66  }
67 
68  m_condition.notify_all();
69  for(std::thread& worker: m_workers)
70  {
71  worker.join();
72  }
73 }
74 
75 //-----------------------------------------------------------------------------
76 
78 {
80  return *poolInstance;
81 }
82 
83 //-----------------------------------------------------------------------------
84 
85 } //namespace fwThread
FWTHREAD_API Pool & getDefaultPool()
Get the default pool.
Definition: Pool.cpp:77
static InstanceSptrType getInstance()
Returns the singleton instance. This method is thread safe.
STL namespace.
FWTHREAD_API Pool()
this constructor launches as much as possible workers
Definition: Pool.cpp:17
This class creates and manages a pool of threads which process tasks.
Definition: Pool.hpp:32
FWTHREAD_API ~Pool()
the destructor joins all threads
Definition: Pool.cpp:61
This namespace fwThread provides few tools to execute asynchronous tasks on different threads...
#define OSLM_WARN_IF(message, cond)
Definition: spyLog.hpp:267
This file defines SpyLog macros. These macros are used to log messages to a file or to the console du...