You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

479 lines
19 KiB

  1. /*
  2. Copyright 2005-2014 Intel Corporation. All Rights Reserved.
  3. This file is part of Threading Building Blocks.
  4. Threading Building Blocks is free software; you can redistribute it
  5. and/or modify it under the terms of the GNU General Public License
  6. version 2 as published by the Free Software Foundation.
  7. Threading Building Blocks is distributed in the hope that it will be
  8. useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  9. of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with Threading Building Blocks; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. As a special exception, you may use this file as part of a free software
  15. library without restriction. Specifically, if other files instantiate
  16. templates or use macros or inline functions from this file, or you compile
  17. this file and link it with other files to produce an executable, this
  18. file does not by itself cause the resulting executable to be covered by
  19. the GNU General Public License. This exception does not however
  20. invalidate any other reasons why the executable file might be covered by
  21. the GNU General Public License.
  22. */
  23. #ifndef __TBB_partitioner_H
  24. #define __TBB_partitioner_H
  25. #ifndef __TBB_INITIAL_CHUNKS
  26. #define __TBB_INITIAL_CHUNKS 2
  27. #endif
  28. #ifndef __TBB_RANGE_POOL_CAPACITY
  29. #define __TBB_RANGE_POOL_CAPACITY 8
  30. #endif
  31. #ifndef __TBB_INIT_DEPTH
  32. #define __TBB_INIT_DEPTH 5
  33. #endif
  34. #include "task.h"
  35. #include "aligned_space.h"
  36. #include "atomic.h"
  37. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  38. // Workaround for overzealous compiler warnings
  39. #pragma warning (push)
  40. #pragma warning (disable: 4244)
  41. #endif
  42. namespace tbb {
  43. class auto_partitioner;
  44. class simple_partitioner;
  45. class affinity_partitioner;
  46. namespace interface6 {
  47. namespace internal {
  48. class affinity_partition_type;
  49. }
  50. }
  51. namespace internal { //< @cond INTERNAL
  52. size_t __TBB_EXPORTED_FUNC get_initial_auto_partitioner_divisor();
  53. //! Defines entry point for affinity partitioner into tbb run-time library.
  54. class affinity_partitioner_base_v3: no_copy {
  55. friend class tbb::affinity_partitioner;
  56. friend class tbb::interface6::internal::affinity_partition_type;
  57. //! Array that remembers affinities of tree positions to affinity_id.
  58. /** NULL if my_size==0. */
  59. affinity_id* my_array;
  60. //! Number of elements in my_array.
  61. size_t my_size;
  62. //! Zeros the fields.
  63. affinity_partitioner_base_v3() : my_array(NULL), my_size(0) {}
  64. //! Deallocates my_array.
  65. ~affinity_partitioner_base_v3() {resize(0);}
  66. //! Resize my_array.
  67. /** Retains values if resulting size is the same. */
  68. void __TBB_EXPORTED_METHOD resize( unsigned factor );
  69. };
  70. //! Provides backward-compatible methods for partition objects without affinity.
  71. class partition_type_base {
  72. public:
  73. void set_affinity( task & ) {}
  74. void note_affinity( task::affinity_id ) {}
  75. task* continue_after_execute_range() {return NULL;}
  76. bool decide_whether_to_delay() {return false;}
  77. void spawn_or_delay( bool, task& b ) {
  78. task::spawn(b);
  79. }
  80. };
  81. template<typename Range, typename Body, typename Partitioner> class start_scan;
  82. } //< namespace internal @endcond
  83. namespace serial {
  84. namespace interface6 {
  85. template<typename Range, typename Body, typename Partitioner> class start_for;
  86. }
  87. }
  88. namespace interface6 {
  89. //! @cond INTERNAL
  90. namespace internal {
  91. using namespace tbb::internal;
  92. template<typename Range, typename Body, typename Partitioner> class start_for;
  93. template<typename Range, typename Body, typename Partitioner> class start_reduce;
  94. //! Join task node that contains shared flag for stealing feedback
  95. class flag_task: public task {
  96. public:
  97. tbb::atomic<bool> my_child_stolen;
  98. flag_task() { my_child_stolen = false; }
  99. task* execute() { return NULL; }
  100. static void mark_task_stolen(task &t) {
  101. tbb::atomic<bool> &flag = static_cast<flag_task*>(t.parent())->my_child_stolen;
  102. #if TBB_USE_THREADING_TOOLS
  103. // Threading tools respect lock prefix but report false-positive data-race via plain store
  104. flag.fetch_and_store<release>(true);
  105. #else
  106. flag = true;
  107. #endif //TBB_USE_THREADING_TOOLS
  108. }
  109. static bool is_peer_stolen(task &t) {
  110. return static_cast<flag_task*>(t.parent())->my_child_stolen;
  111. }
  112. };
  113. //! Depth is a relative depth of recursive division inside a range pool. Relative depth allows
  114. //! infinite absolute depth of the recursion for heavily imbalanced workloads with range represented
  115. //! by a number that cannot fit into machine word.
  116. typedef unsigned char depth_t;
  117. //! Range pool stores ranges of type T in a circular buffer with MaxCapacity
  118. template <typename T, depth_t MaxCapacity>
  119. class range_vector {
  120. depth_t my_head;
  121. depth_t my_tail;
  122. depth_t my_size;
  123. depth_t my_depth[MaxCapacity]; // relative depths of stored ranges
  124. tbb::aligned_space<T, MaxCapacity> my_pool;
  125. public:
  126. //! initialize via first range in pool
  127. range_vector(const T& elem) : my_head(0), my_tail(0), my_size(1) {
  128. my_depth[0] = 0;
  129. new( my_pool.begin() ) T(elem);//TODO: std::move?
  130. }
  131. ~range_vector() {
  132. while( !empty() ) pop_back();
  133. }
  134. bool empty() const { return my_size == 0; }
  135. depth_t size() const { return my_size; }
  136. //! Populates range pool via ranges up to max depth or while divisible
  137. //! max_depth starts from 0, e.g. value 2 makes 3 ranges in the pool up to two 1/4 pieces
  138. void split_to_fill(depth_t max_depth) {
  139. while( my_size < MaxCapacity && my_depth[my_head] < max_depth
  140. && my_pool.begin()[my_head].is_divisible() ) {
  141. depth_t prev = my_head;
  142. my_head = (my_head + 1) % MaxCapacity;
  143. new(my_pool.begin()+my_head) T(my_pool.begin()[prev]); // copy TODO: std::move?
  144. my_pool.begin()[prev].~T(); // instead of assignment
  145. new(my_pool.begin()+prev) T(my_pool.begin()[my_head], split()); // do 'inverse' split
  146. my_depth[my_head] = ++my_depth[prev];
  147. my_size++;
  148. }
  149. }
  150. void pop_back() {
  151. __TBB_ASSERT(my_size > 0, "range_vector::pop_back() with empty size");
  152. my_pool.begin()[my_head].~T();
  153. my_size--;
  154. my_head = (my_head + MaxCapacity - 1) % MaxCapacity;
  155. }
  156. void pop_front() {
  157. __TBB_ASSERT(my_size > 0, "range_vector::pop_front() with empty size");
  158. my_pool.begin()[my_tail].~T();
  159. my_size--;
  160. my_tail = (my_tail + 1) % MaxCapacity;
  161. }
  162. T& back() {
  163. __TBB_ASSERT(my_size > 0, "range_vector::back() with empty size");
  164. return my_pool.begin()[my_head];
  165. }
  166. T& front() {
  167. __TBB_ASSERT(my_size > 0, "range_vector::front() with empty size");
  168. return my_pool.begin()[my_tail];
  169. }
  170. //! similarly to front(), returns depth of the first range in the pool
  171. depth_t front_depth() {
  172. __TBB_ASSERT(my_size > 0, "range_vector::front_depth() with empty size");
  173. return my_depth[my_tail];
  174. }
  175. };
  176. //! Provides default methods for partition objects and common algorithm blocks.
  177. template <typename Partition>
  178. struct partition_type_base {
  179. // decision makers
  180. void set_affinity( task & ) {}
  181. void note_affinity( task::affinity_id ) {}
  182. bool check_being_stolen(task &) { return false; } // part of old should_execute_range()
  183. bool check_for_demand(task &) { return false; }
  184. bool is_divisible() { return true; } // part of old should_execute_range()
  185. depth_t max_depth() { return 0; }
  186. void align_depth(depth_t) { }
  187. // common function blocks
  188. Partition& self() { return *static_cast<Partition*>(this); } // CRTP helper
  189. template<typename StartType, typename Range>
  190. void execute(StartType &start, Range &range) {
  191. // The algorithm in a few words ([]-denotes calls to decision methods of partitioner):
  192. // [If this task is stolen, adjust depth and divisions if necessary, set flag].
  193. // If range is divisible {
  194. // Spread the work while [initial divisions left];
  195. // Create trap task [if necessary];
  196. // }
  197. // If not divisible or [max depth is reached], execute, else do the range pool part
  198. if ( range.is_divisible() ) {
  199. if ( self().is_divisible() )
  200. do start.offer_work( split() ); // split until is divisible
  201. while ( range.is_divisible() && self().is_divisible() );
  202. }
  203. if( !range.is_divisible() || !self().max_depth() )
  204. start.run_body( range ); // simple partitioner goes always here
  205. else { // do range pool
  206. internal::range_vector<Range, Partition::range_pool_size> range_pool(range);
  207. do {
  208. range_pool.split_to_fill(self().max_depth()); // fill range pool
  209. if( self().check_for_demand( start ) ) {
  210. if( range_pool.size() > 1 ) {
  211. start.offer_work( range_pool.front(), range_pool.front_depth() );
  212. range_pool.pop_front();
  213. continue;
  214. }
  215. if( range_pool.back().is_divisible() ) // was not enough depth to fork a task
  216. continue; // note: check_for_demand() should guarantee increasing max_depth() next time
  217. }
  218. start.run_body( range_pool.back() );
  219. range_pool.pop_back();
  220. } while( !range_pool.empty() && !start.is_cancelled() );
  221. }
  222. }
  223. };
  224. //! Provides default methods for auto (adaptive) partition objects.
  225. template <typename Partition>
  226. struct auto_partition_type_base : partition_type_base<Partition> {
  227. size_t my_divisor;
  228. depth_t my_max_depth;
  229. auto_partition_type_base() : my_max_depth(__TBB_INIT_DEPTH) {
  230. my_divisor = tbb::internal::get_initial_auto_partitioner_divisor()*__TBB_INITIAL_CHUNKS/4;
  231. __TBB_ASSERT(my_divisor, "initial value of get_initial_auto_partitioner_divisor() is not valid");
  232. }
  233. auto_partition_type_base(auto_partition_type_base &src, split) {
  234. my_max_depth = src.my_max_depth;
  235. #if __TBB_INITIAL_TASK_IMBALANCE
  236. if( src.my_divisor <= 1 ) my_divisor = 0;
  237. else my_divisor = src.my_divisor = (src.my_divisor+1u) / 2u;
  238. #else
  239. my_divisor = src.my_divisor / 2u;
  240. src.my_divisor = src.my_divisor - my_divisor; // TODO: check the effect separately
  241. if(my_divisor) src.my_max_depth += static_cast<depth_t>(__TBB_Log2(src.my_divisor/my_divisor));
  242. #endif
  243. }
  244. bool check_being_stolen( task &t) { // part of old should_execute_range()
  245. if( !my_divisor ) { // if not from the top P tasks of binary tree
  246. my_divisor = 1; // TODO: replace by on-stack flag (partition_state's member)?
  247. if( t.is_stolen_task() ) {
  248. #if TBB_USE_EXCEPTIONS
  249. // RTTI is available, check whether the cast is valid
  250. __TBB_ASSERT(dynamic_cast<flag_task*>(t.parent()), 0);
  251. // correctness of the cast relies on avoiding the root task for which:
  252. // - initial value of my_divisor != 0 (protected by separate assertion)
  253. // - is_stolen_task() always returns false for the root task.
  254. #endif
  255. flag_task::mark_task_stolen(t);
  256. my_max_depth++;
  257. return true;
  258. }
  259. }
  260. return false;
  261. }
  262. bool is_divisible() { // part of old should_execute_range()
  263. if( my_divisor > 1 ) return true;
  264. if( my_divisor && my_max_depth > 1 ) { // can split the task and once more internally. TODO: on-stack flag instead
  265. // keep same fragmentation while splitting for the local task pool
  266. my_max_depth--;
  267. my_divisor = 0; // decrease max_depth once per task
  268. return true;
  269. } else return false;
  270. }
  271. bool check_for_demand(task &t) {
  272. if( flag_task::is_peer_stolen(t) ) {
  273. my_max_depth++;
  274. return true;
  275. } else return false;
  276. }
  277. void align_depth(depth_t base) {
  278. __TBB_ASSERT(base <= my_max_depth, 0);
  279. my_max_depth -= base;
  280. }
  281. depth_t max_depth() { return my_max_depth; }
  282. };
  283. //! Provides default methods for affinity (adaptive) partition objects.
  284. class affinity_partition_type : public auto_partition_type_base<affinity_partition_type> {
  285. static const unsigned factor_power = 4;
  286. static const unsigned factor = 1<<factor_power;
  287. bool my_delay;
  288. unsigned map_begin, map_end, map_mid;
  289. tbb::internal::affinity_id* my_array;
  290. void set_mid() {
  291. unsigned d = (map_end - map_begin)/2; // we could add 1 but it is rather for LIFO affinity
  292. if( d > factor )
  293. d &= 0u-factor;
  294. map_mid = map_end - d;
  295. }
  296. public:
  297. affinity_partition_type( tbb::internal::affinity_partitioner_base_v3& ap ) {
  298. __TBB_ASSERT( (factor&(factor-1))==0, "factor must be power of two" );
  299. ap.resize(factor);
  300. my_array = ap.my_array;
  301. map_begin = 0;
  302. map_end = unsigned(ap.my_size);
  303. set_mid();
  304. my_delay = true;
  305. my_divisor /= __TBB_INITIAL_CHUNKS; // let exactly P tasks to be distributed across workers
  306. my_max_depth = factor_power+1; // the first factor_power ranges will be spawned, and >=1 ranges should be left
  307. __TBB_ASSERT( my_max_depth < __TBB_RANGE_POOL_CAPACITY, 0 );
  308. }
  309. affinity_partition_type(affinity_partition_type& p, split)
  310. : auto_partition_type_base<affinity_partition_type>(p, split()), my_array(p.my_array) {
  311. __TBB_ASSERT( p.map_end-p.map_begin<factor || (p.map_end-p.map_begin)%factor==0, NULL );
  312. map_end = p.map_end;
  313. map_begin = p.map_end = p.map_mid;
  314. set_mid(); p.set_mid();
  315. my_delay = p.my_delay;
  316. }
  317. void set_affinity( task &t ) {
  318. if( map_begin<map_end )
  319. t.set_affinity( my_array[map_begin] );
  320. }
  321. void note_affinity( task::affinity_id id ) {
  322. if( map_begin<map_end )
  323. my_array[map_begin] = id;
  324. }
  325. bool check_for_demand( task &t ) {
  326. if( !my_delay ) {
  327. if( map_mid<map_end ) {
  328. __TBB_ASSERT(my_max_depth>__TBB_Log2(map_end-map_mid), 0);
  329. return true;// do not do my_max_depth++ here, but be sure my_max_depth is big enough
  330. }
  331. if( flag_task::is_peer_stolen(t) ) {
  332. my_max_depth++;
  333. return true;
  334. }
  335. } else my_delay = false;
  336. return false;
  337. }
  338. bool is_divisible() {
  339. return my_divisor > 1;
  340. }
  341. static const unsigned range_pool_size = __TBB_RANGE_POOL_CAPACITY;
  342. };
  343. class auto_partition_type: public auto_partition_type_base<auto_partition_type> {
  344. public:
  345. auto_partition_type( const auto_partitioner& ) {}
  346. auto_partition_type( auto_partition_type& src, split)
  347. : auto_partition_type_base<auto_partition_type>(src, split()) {}
  348. static const unsigned range_pool_size = __TBB_RANGE_POOL_CAPACITY;
  349. };
  350. class simple_partition_type: public partition_type_base<simple_partition_type> {
  351. public:
  352. simple_partition_type( const simple_partitioner& ) {}
  353. simple_partition_type( const simple_partition_type&, split ) {}
  354. //! simplified algorithm
  355. template<typename StartType, typename Range>
  356. void execute(StartType &start, Range &range) {
  357. while( range.is_divisible() )
  358. start.offer_work( split() );
  359. start.run_body( range );
  360. }
  361. //static const unsigned range_pool_size = 1; - not necessary because execute() is overridden
  362. };
  363. //! Backward-compatible partition for auto and affinity partition objects.
  364. class old_auto_partition_type: public tbb::internal::partition_type_base {
  365. size_t num_chunks;
  366. static const size_t VICTIM_CHUNKS = 4;
  367. public:
  368. bool should_execute_range(const task &t) {
  369. if( num_chunks<VICTIM_CHUNKS && t.is_stolen_task() )
  370. num_chunks = VICTIM_CHUNKS;
  371. return num_chunks==1;
  372. }
  373. old_auto_partition_type( const auto_partitioner& )
  374. : num_chunks(internal::get_initial_auto_partitioner_divisor()*__TBB_INITIAL_CHUNKS/4) {}
  375. old_auto_partition_type( const affinity_partitioner& )
  376. : num_chunks(internal::get_initial_auto_partitioner_divisor()*__TBB_INITIAL_CHUNKS/4) {}
  377. old_auto_partition_type( old_auto_partition_type& pt, split ) {
  378. num_chunks = pt.num_chunks = (pt.num_chunks+1u) / 2u;
  379. }
  380. };
  381. } // namespace interfaceX::internal
  382. //! @endcond
  383. } // namespace interfaceX
  384. //! A simple partitioner
  385. /** Divides the range until the range is not divisible.
  386. @ingroup algorithms */
  387. class simple_partitioner {
  388. public:
  389. simple_partitioner() {}
  390. private:
  391. template<typename Range, typename Body, typename Partitioner> friend class serial::interface6::start_for;
  392. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_for;
  393. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_reduce;
  394. template<typename Range, typename Body, typename Partitioner> friend class internal::start_scan;
  395. // backward compatibility
  396. class partition_type: public internal::partition_type_base {
  397. public:
  398. bool should_execute_range(const task& ) {return false;}
  399. partition_type( const simple_partitioner& ) {}
  400. partition_type( const partition_type&, split ) {}
  401. };
  402. // new implementation just extends existing interface
  403. typedef interface6::internal::simple_partition_type task_partition_type;
  404. };
  405. //! An auto partitioner
  406. /** The range is initial divided into several large chunks.
  407. Chunks are further subdivided into smaller pieces if demand detected and they are divisible.
  408. @ingroup algorithms */
  409. class auto_partitioner {
  410. public:
  411. auto_partitioner() {}
  412. private:
  413. template<typename Range, typename Body, typename Partitioner> friend class serial::interface6::start_for;
  414. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_for;
  415. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_reduce;
  416. template<typename Range, typename Body, typename Partitioner> friend class internal::start_scan;
  417. // backward compatibility
  418. typedef interface6::internal::old_auto_partition_type partition_type;
  419. // new implementation just extends existing interface
  420. typedef interface6::internal::auto_partition_type task_partition_type;
  421. };
  422. //! An affinity partitioner
  423. class affinity_partitioner: internal::affinity_partitioner_base_v3 {
  424. public:
  425. affinity_partitioner() {}
  426. private:
  427. template<typename Range, typename Body, typename Partitioner> friend class serial::interface6::start_for;
  428. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_for;
  429. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_reduce;
  430. template<typename Range, typename Body, typename Partitioner> friend class internal::start_scan;
  431. // backward compatibility - for parallel_scan only
  432. typedef interface6::internal::old_auto_partition_type partition_type;
  433. // new implementation just extends existing interface
  434. typedef interface6::internal::affinity_partition_type task_partition_type;
  435. };
  436. } // namespace tbb
  437. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  438. #pragma warning (pop)
  439. #endif // warning 4244 is back
  440. #undef __TBB_INITIAL_CHUNKS
  441. #undef __TBB_RANGE_POOL_CAPACITY
  442. #undef __TBB_INIT_DEPTH
  443. #endif /* __TBB_partitioner_H */