ThreadPoolSvc.cpp
Go to the documentation of this file.
1 #include "ThreadPoolSvc.h"
2 
4 #include "ThreadInitTask.h"
5 
6 #include "tbb/task_scheduler_init.h"
7 #include "tbb/task_scheduler_observer.h"
8 #include "tbb/task.h"
9 #include "tbb/tick_count.h"
10 #include "tbb/tbb_thread.h"
11 
12 using namespace tbb;
13 
15 
16 //=============================================================================
17 
18 
19 ThreadPoolSvc::ThreadPoolSvc( const std::string& name, ISvcLocator* svcLoc ):
20  base_class(name,svcLoc),
21  m_threadInitTools(this),
22  m_init(false),
23  m_threadPoolSize(0),
24  m_tbbSchedInit(nullptr),
25  m_barrier(nullptr)
26 {
27 
28  declareProperty("ThreadInitTools", m_threadInitTools,
29  "ToolHandleArray of IThreadInitTools");
30 
31 }
32 
33 //-----------------------------------------------------------------------------
34 
37 
38  // Initialise mother class (read properties, ...)
40  if (!sc.isSuccess()) {
41  warning () << "Base class could not be initialized" << endmsg;
42  return StatusCode::FAILURE;
43  }
44 
45  if (m_threadInitTools.retrieve().isFailure()) {
46  error() << "Unable to retrieve ThreadInitTools Array" << endmsg;
47 
48  return StatusCode::FAILURE;
49  } else {
50  if (m_threadInitTools.size() != 0) {
51  info() << "retrieved " << m_threadInitTools.size() << " thread init tools"
52  << endmsg;
53  } else {
54  info() << "no thread init tools attached" << endmsg;
55  }
56  }
57 
58  return StatusCode::SUCCESS;
59 
60 }
61 
62 //-----------------------------------------------------------------------------
63 
66 
67  if (!m_init) {
68  warning() << "Looks like the ThreadPoolSvc was created, but thread pool "
69  << "was never initialized" << endmsg;
70  }
71 
72  return StatusCode::SUCCESS;
73 
74 }
75 
76 //-----------------------------------------------------------------------------
77 
79 ThreadPoolSvc::initPool(const int& poolSize) {
80 
81  tbb::spin_mutex::scoped_lock lock( m_initMutex );
82 
83  m_threadPoolSize = poolSize;
84 
85  if (msgLevel(MSG::DEBUG))
86  debug() << "ThreadPoolSvc::initPool() poolSize = " << poolSize << endmsg;
87  //There is a problem in the piece of the code below. if
88  // m_threadPoolSize is set to something negative which is < -1,
89  // algorithm below might not behave as expected. For the time being
90  // I've choosen to create the barrier with the default number of
91  // threads created by the task scheduler init assuming that a
92  // negative value will choose automatic thread creation which will
93  // create default number of threads.
94  // SK
95 
96  // -100 prevents the creation of the pool and the scheduler directly
97  // executes the tasks.
98  if (-100 != m_threadPoolSize) {
99  if (msgLevel(MSG::DEBUG))
100  debug() << "Initialising a thread pool of size "
101  << m_threadPoolSize << endmsg;
102 
103  // Leave -1 in case selected, increment otherwise
104  // - What?
105  int thePoolSize = m_threadPoolSize;
106  if (thePoolSize != -1) thePoolSize += 1;
107 
108 
109  // Create the TBB task scheduler
110  m_tbbSchedInit = std::unique_ptr<tbb::task_scheduler_init>( new tbb::task_scheduler_init(thePoolSize) );
111  // Create the barrier for task synchronization
112  if(m_threadPoolSize<=-1)thePoolSize=m_tbbSchedInit->default_num_threads();
113  if (msgLevel(MSG::DEBUG)){
114  debug() << "creating barrier of size " << thePoolSize << endmsg;
115  }
116  m_barrier = std::unique_ptr<boost::barrier>( new boost::barrier(thePoolSize) );
117 
118  }
119 
120  // Launch the init tool tasks
121  const bool terminate = false;
122  if (launchTasks(terminate).isFailure())
123  return StatusCode::FAILURE;
124 
125  if (msgLevel(MSG::DEBUG))
126  debug() << "Thread Pool initialization complete!" << endmsg;
127 
128  m_init = true;
129 
130  return StatusCode::SUCCESS;
131 
132 }
133 
134 //-----------------------------------------------------------------------------
135 
138  tbb::spin_mutex::scoped_lock lock( m_initMutex );
139  if (msgLevel(MSG::DEBUG))
140  debug() << "ThreadPoolSvc::terminatePool()" << endmsg;
141 
142  if (!m_init) {
143  error() << "Trying to terminate uninitialized thread pool!" << endmsg;
144  return StatusCode::FAILURE;
145  }
146 
147  // Launch the termination tasks
148  const bool terminate = true;
149  if (launchTasks(terminate).isFailure())
150  return StatusCode::FAILURE;
151 
152  if (msgLevel(MSG::DEBUG))
153  debug() << "Thread pool termination complete!" << endmsg;
154 
155  return StatusCode::SUCCESS;
156 }
157 
158 //-----------------------------------------------------------------------------
159 
161 ThreadPoolSvc::launchTasks(bool terminate) {
162 
163  if (m_threadInitTools.empty()) return StatusCode::SUCCESS;
164 
165  const std::string taskType = terminate ? "termination" : "initialization";
166 
167  // If we have a thread pool (via a scheduler), then we want to queue
168  // the tasks in TBB to execute on each thread.
169  if(m_tbbSchedInit) {
170 
171  // Create one task for each worker thread in the pool
172  for (int i = 0; i < m_threadPoolSize; ++i) {
173  if (msgLevel(MSG::DEBUG))
174  debug() << "creating ThreadInitTask " << i << endmsg;
175  tbb::task* t = new(tbb::task::allocate_root())
176  ThreadInitTask( m_threadInitTools, m_barrier.get(), serviceLocator(), terminate );
177 
178  // Queue the task
179  tbb::task::enqueue( *t );
180  this_tbb_thread::sleep(tbb::tick_count::interval_t(.1));
181  }
182 
183  // Now wait for all the workers to reach the barrier
184  if (msgLevel(MSG::DEBUG))
185  debug() << "waiting at barrier for all ThreadInitTool to finish executing" << endmsg;
186  m_barrier->wait();
187 
188  // Check to make sure all Tools were invoked.
189  // I'm not sure this mechanism is worthwhile.
190  for (auto& t : m_threadInitTools) {
191  // Number of threads initialized but not terminated.
192  int numInit = t->nInit();
193  // Expected number based on the type of task.
194  int expectedNumInit = terminate? 0 : m_threadPoolSize;
195  if (numInit != expectedNumInit) {
196  error() << "not all threads " << (terminate? "terminated" : "initialized")
197  << " for tool " << t << " : "
198  << t->nInit() << " out of " << m_threadPoolSize
199  << " are currently active" << endmsg;
200  return StatusCode::FAILURE;
201  }
202  }
203 
204  }
205 
206  // In single-threaded mode, there is no scheduler, so we simply call
207  // the task wrapper directly in this thread.
208  else {
209  if (msgLevel(MSG::DEBUG))
210  debug() << "launching ThreadInitTask " << taskType << "in this thread." << endmsg;
211  boost::barrier* noBarrier = nullptr;
212  ThreadInitTask theTask(m_threadInitTools, noBarrier, serviceLocator(), terminate);
213  theTask.execute();
214  }
215 
216  // Now, we do some error checking
218  error() << "a ThreadInitTask failed to execute successfully" << endmsg;
219  return StatusCode::FAILURE;
220  }
221 
222  return StatusCode::SUCCESS;
223 }
virtual StatusCode finalize() override final
Finalise.
StatusCode initialize() override
Definition: Service.cpp:64
tbb::task * execute() override
Execute the task.
The ISvcLocator is the interface implemented by the Service Factory in the Application Manager to loc...
Definition: ISvcLocator.h:25
virtual StatusCode terminatePool() override final
Terminate the thread pool and launch thread termination tasks.
bool isSuccess() const
Test for a status code of SUCCESS.
Definition: StatusCode.h:74
Gaudi::Details::PropertyBase * declareProperty(const std::string &name, TYPE &value, const std::string &doc="none")
Declare a property (templated)
Special TBB task used by ThreadPoolSvc to wrap execution of IThreadInitTools.
STL namespace.
STL class.
This class is used for returning status codes from appropriate routines.
Definition: StatusCode.h:26
static bool execFailed()
virtual StatusCode initialize() override final
Initialise.
#define DECLARE_SERVICE_FACTORY(x)
Definition: Service.h:242
A service which initializes a TBB thread pool.
Definition: ThreadPoolSvc.h:26
virtual StatusCode initPool(const int &poolSize) override final
Initialize the thread pool and launch the ThreadInitTasks.
StatusCode launchTasks(bool finalize=false)
Launch tasks to execute the ThreadInitTools.
MsgStream & endmsg(MsgStream &s)
MsgStream Modifier: endmsg. Calls the output method of the MsgStream.
Definition: MsgStream.h:244