Logo ROOT   6.07/09
Reference Guide
threadPool.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_thread
3 ///
4 /// Usage:
5 ///
6 /// ~~~{.cpp}
7 /// root [0] .L threadPool.C++
8 /// root [1] threadPool(10) 10 = numThreads
9 /// ~~~
10 ///
11 /// \macro_code
12 ///
13 /// \author Victor Perevovchikov
14 
15 // STD
16 #include <iostream>
17 #include <iterator>
18 #include <vector>
19 #ifndef _WIN32
20 #include <unistd.h>
21 #endif
22 // ThreadPool
23 #include "TThreadPool.h"
24 // ROOT
25 #include "TThread.h"
26 
27 //=============================================================================
28 using namespace std;
29 //=============================================================================
30 const size_t g_sleeptime = 1; // in secs.
31 const size_t g_multTasks = 50;
32 //=============================================================================
33 
34 // define a custom parameters type for task objects
35 enum EProc {start, clean};
36 
37 // a class defining task objects
38 class TTestTask: public TThreadPoolTaskImp<TTestTask, EProc>
39 {
40 public:
41  bool runTask(EProc /*_param*/) {
42  m_tid = TThread::SelfId();
43  TThread::Sleep(g_sleeptime, 0L);
44  return true;
45  }
46  unsigned long threadID() const {
47  return m_tid;
48  }
49 
50 private:
51  unsigned long m_tid;
52 };
53 
54 //=============================================================================
55 void threadPool(size_t _numThreads = 10, bool _needDbg = false)
56 {
57  cout << "ThreadPool: starting..." << endl;
58  // number of tasks to process
59  size_t numTasks(_numThreads * g_multTasks);
60 
61  // create a thread pool object
62  // _numThreads - a number of threads in the pool
63  // _needDbg - defines whether to show debug messages
64  TThreadPool<TTestTask, EProc> threadPool(_numThreads, _needDbg);
65 
66  // create a container of tasks
67  vector <TTestTask> tasksList(numTasks);
68 
69  cout << "ThreadPool: getting tasks..." << endl;
70  cout << "ThreadPool: processing tasks..." << endl;
71  // push tasks to the ThreadPool
72  // tasks can be also pushed asynchronously
73  for (size_t i = 0; i < numTasks; ++i) {
74  threadPool.PushTask(tasksList[i], start);
75  }
76 
77  // Stop thread pool.
78  // The parameter "true" requests the calling thread to wait,
79  // until the thread pool task queue is drained.
80  threadPool.Stop(true);
81  cout << "ThreadPool: done" << endl;
82 }
83 
RooArgList L(const RooAbsArg &v1)
STL namespace.
static Long_t SelfId()
Static method returning the id for the current thread.
Definition: TThread.cxx:538
static Int_t Sleep(ULong_t secs, ULong_t nanos=0)
Static method to sleep the calling thread.
Definition: TThread.cxx:736