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