fw4spl
RegionThreader.hpp
1 /* ***** BEGIN LICENSE BLOCK *****
2  * FW4SPL - Copyright (C) IRCAD, 2009-2015.
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 #ifndef __FWDATATOOLS_THREAD_REGIONTHREADER_HPP__
8 #define __FWDATATOOLS_THREAD_REGIONTHREADER_HPP__
9 
10 #include <algorithm>
11 #include <cstddef>
12 #include <limits>
13 #include <thread>
14 #include <vector>
15 
16 namespace fwDataTools
17 {
18 
19 namespace thread
20 {
21 
22 
24 {
25 
26 public:
27 
29  : m_nbThread( (std::thread::hardware_concurrency() > 1) ? std::thread::hardware_concurrency() : 1 )
30  {
31  }
32 
33  RegionThreader(size_t nbThread, bool capped = true)
34  : m_nbThread( std::min( capped ? std::thread::hardware_concurrency() : std::numeric_limits<size_t>::max(),
35  (nbThread > 1) ? nbThread : 1) )
36  {
37  }
38 
39  template<typename T> void operator()(T func, const size_t dataSize)
40  {
41  std::vector< std::thread* > threads;
42 
43  const size_t step = (dataSize / m_nbThread) + 1;
44  size_t regionBegin = 0;
45  size_t threadId = 0;
46 
47  if (m_nbThread > 1)
48  {
49  for (; regionBegin < dataSize; regionBegin += step, ++threadId)
50  {
51  threads.push_back(new std::thread(func, regionBegin, std::min( dataSize, regionBegin + step),
52  threadId ));
53  }
54 
55  for( std::thread *thread: threads)
56  {
57  thread->join();
58  delete thread;
59  }
60  threads.clear();
61  }
62  else
63  {
64  func(0, dataSize, 0);
65  }
66  }
67 
68  size_t numberOfThread()
69  {
70  return m_nbThread;
71  }
72 
73 protected:
74 
75  const size_t m_nbThread;
76 };
77 
78 } // namespace thread
79 
80 } // namespace fwDataTools
81 
82 
83 #endif //__FWDATATOOLS_THREAD_REGIONTHREADER_HPP__
84 
The namespace fwDataTools contains classes which provide helpers to manipulate fwData::Object. *.