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.

521 lines
21 KiB

  1. /*
  2. Copyright 2005-2013 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 {
  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
  83. //! @endcond
  84. namespace serial {
  85. namespace interface6 {
  86. template<typename Range, typename Body, typename Partitioner> class start_for;
  87. }
  88. }
  89. namespace interface6 {
  90. //! @cond INTERNAL
  91. namespace internal {
  92. using namespace tbb::internal;
  93. template<typename Range, typename Body, typename Partitioner> class start_for;
  94. template<typename Range, typename Body, typename Partitioner> class start_reduce;
  95. //! Join task node that contains shared flag for stealing feedback
  96. class flag_task: public task {
  97. public:
  98. tbb::atomic<bool> my_child_stolen;
  99. flag_task() { my_child_stolen = false; }
  100. task* execute() { return NULL; }
  101. static void mark_task_stolen(task &t) {
  102. tbb::atomic<bool> &flag = static_cast<flag_task*>(t.parent())->my_child_stolen;
  103. #if TBB_USE_THREADING_TOOLS
  104. // Threading tools respect lock prefix but report false-positive data-race via plain store
  105. flag.fetch_and_store<release>(true);
  106. #else
  107. flag = true;
  108. #endif //TBB_USE_THREADING_TOOLS
  109. }
  110. static bool is_peer_stolen(task &t) {
  111. return static_cast<flag_task*>(t.parent())->my_child_stolen;
  112. }
  113. };
  114. //! Task to signal the demand without carrying the work
  115. class signal_task: public task {
  116. public:
  117. task* execute() {
  118. if( is_stolen_task() ) {
  119. flag_task::mark_task_stolen(*this);
  120. }
  121. return NULL;
  122. }
  123. };
  124. //! Depth is a relative depth of recursive division inside a range pool. Relative depth allows
  125. //! infinite absolute depth of the recursion for heavily imbalanced workloads with range represented
  126. //! by a number that cannot fit into machine word.
  127. typedef unsigned char depth_t;
  128. //! Range pool stores ranges of type T in a circular buffer with MaxCapacity
  129. template <typename T, depth_t MaxCapacity>
  130. class range_vector {
  131. depth_t my_head;
  132. depth_t my_tail;
  133. depth_t my_size;
  134. depth_t my_depth[MaxCapacity]; // relative depths of stored ranges
  135. tbb::aligned_space<T, MaxCapacity> my_pool;
  136. public:
  137. //! initialize via first range in pool
  138. range_vector(const T& elem) : my_head(0), my_tail(0), my_size(1) {
  139. my_depth[0] = 0;
  140. new( my_pool.begin() ) T(elem);//TODO: std::move?
  141. }
  142. ~range_vector() {
  143. while( !empty() ) pop_back();
  144. }
  145. bool empty() const { return my_size == 0; }
  146. depth_t size() const { return my_size; }
  147. //! Populates range pool via ranges up to max depth or while divisible
  148. //! max_depth starts from 0, e.g. value 2 makes 3 ranges in the pool up to two 1/4 pieces
  149. void split_to_fill(depth_t max_depth) {
  150. while( my_size < MaxCapacity && my_depth[my_head] < max_depth
  151. && my_pool.begin()[my_head].is_divisible() ) {
  152. depth_t prev = my_head;
  153. my_head = (my_head + 1) % MaxCapacity;
  154. new(my_pool.begin()+my_head) T(my_pool.begin()[prev]); // copy TODO: std::move?
  155. my_pool.begin()[prev].~T(); // instead of assignment
  156. new(my_pool.begin()+prev) T(my_pool.begin()[my_head], split()); // do 'inverse' split
  157. my_depth[my_head] = ++my_depth[prev];
  158. my_size++;
  159. }
  160. }
  161. void pop_back() {
  162. __TBB_ASSERT(my_size > 0, "range_vector::pop_back() with empty size");
  163. my_pool.begin()[my_head].~T();
  164. my_size--;
  165. my_head = (my_head + MaxCapacity - 1) % MaxCapacity;
  166. }
  167. void pop_front() {
  168. __TBB_ASSERT(my_size > 0, "range_vector::pop_front() with empty size");
  169. my_pool.begin()[my_tail].~T();
  170. my_size--;
  171. my_tail = (my_tail + 1) % MaxCapacity;
  172. }
  173. T& back() {
  174. __TBB_ASSERT(my_size > 0, "range_vector::back() with empty size");
  175. return my_pool.begin()[my_head];
  176. }
  177. T& front() {
  178. __TBB_ASSERT(my_size > 0, "range_vector::front() with empty size");
  179. return my_pool.begin()[my_tail];
  180. }
  181. //! similarly to front(), returns depth of the first range in the pool
  182. depth_t front_depth() {
  183. __TBB_ASSERT(my_size > 0, "range_vector::front_depth() with empty size");
  184. return my_depth[my_tail];
  185. }
  186. };
  187. //! Provides default methods for partition objects and common algorithm blocks.
  188. template <typename Partition>
  189. struct partition_type_base {
  190. // decision makers
  191. void set_affinity( task & ) {}
  192. void note_affinity( task::affinity_id ) {}
  193. bool check_being_stolen(task &) { return false; } // part of old should_execute_range()
  194. bool check_for_demand(task &) { return false; }
  195. bool divisions_left() { return true; } // part of old should_execute_range()
  196. bool should_create_trap() { return false; }
  197. depth_t max_depth() { return 0; }
  198. void align_depth(depth_t) { }
  199. // common function blocks
  200. Partition& derived() { return *static_cast<Partition*>(this); }
  201. template<typename StartType>
  202. flag_task* split_work(StartType &start) {
  203. flag_task* parent_ptr = start.create_continuation(); // the type here is to express expectation
  204. start.set_parent(parent_ptr);
  205. parent_ptr->set_ref_count(2);
  206. StartType& right_work = *new( parent_ptr->allocate_child() ) StartType(start, split());
  207. start.spawn(right_work);
  208. return parent_ptr;
  209. }
  210. template<typename StartType, typename Range>
  211. void execute(StartType &start, Range &range) {
  212. // The algorithm in a few words ([]-denotes calls to decision methods of partitioner):
  213. // [If this task is stolen, adjust depth and divisions if necessary, set flag].
  214. // If range is divisible {
  215. // Spread the work while [initial divisions left];
  216. // Create trap task [if necessary];
  217. // }
  218. // If not divisible or [max depth is reached], execute, else do the range pool part
  219. task* parent_ptr = start.parent();
  220. if( range.is_divisible() ) {
  221. if( derived().divisions_left() )
  222. do parent_ptr = split_work(start); // split until divisions_left()
  223. while( range.is_divisible() && derived().divisions_left() );
  224. if( derived().should_create_trap() ) { // only for range pool
  225. if( parent_ptr->ref_count() > 1 ) { // create new parent if necessary
  226. parent_ptr = start.create_continuation();
  227. start.set_parent(parent_ptr);
  228. } else __TBB_ASSERT(parent_ptr->ref_count() == 1, NULL);
  229. parent_ptr->set_ref_count(2); // safe because parent has only one reference
  230. signal_task& right_signal = *new( parent_ptr->allocate_child() ) signal_task();
  231. start.spawn(right_signal); // pure signal is to avoid deep recursion in the end
  232. }
  233. }
  234. if( !range.is_divisible() || !derived().max_depth() )
  235. start.run_body( range ); // simple partitioner goes always here
  236. else { // do range pool
  237. internal::range_vector<Range, Partition::range_pool_size> range_pool(range);
  238. do {
  239. range_pool.split_to_fill(derived().max_depth()); // fill range pool
  240. if( derived().check_for_demand( start ) ) {
  241. if( range_pool.size() > 1 ) {
  242. parent_ptr = start.create_continuation();
  243. start.set_parent(parent_ptr);
  244. parent_ptr->set_ref_count(2);
  245. StartType& right_work = *new( parent_ptr->allocate_child() ) StartType(start, range_pool.front(), range_pool.front_depth());
  246. start.spawn(right_work);
  247. range_pool.pop_front();
  248. continue;
  249. }
  250. if( range_pool.back().is_divisible() ) // was not enough depth to fork a task
  251. continue; // note: check_for_demand() should guarantee increasing max_depth() next time
  252. }
  253. start.run_body( range_pool.back() );
  254. range_pool.pop_back();
  255. } while( !range_pool.empty() && !start.is_cancelled() );
  256. }
  257. }
  258. };
  259. //! Provides default methods for auto (adaptive) partition objects.
  260. template <typename Partition>
  261. struct auto_partition_type_base : partition_type_base<Partition> {
  262. size_t my_divisor;
  263. depth_t my_max_depth;
  264. auto_partition_type_base() : my_max_depth(__TBB_INIT_DEPTH) {
  265. my_divisor = tbb::internal::get_initial_auto_partitioner_divisor()*__TBB_INITIAL_CHUNKS/4;
  266. __TBB_ASSERT(my_divisor, "initial value of get_initial_auto_partitioner_divisor() is not valid");
  267. }
  268. auto_partition_type_base(auto_partition_type_base &src, split) {
  269. my_max_depth = src.my_max_depth;
  270. #if __TBB_INITIAL_TASK_IMBALANCE
  271. if( src.my_divisor <= 1 ) my_divisor = 0;
  272. else my_divisor = src.my_divisor = (src.my_divisor+1u) / 2u;
  273. #else
  274. my_divisor = src.my_divisor / 2u;
  275. src.my_divisor = src.my_divisor - my_divisor; // TODO: check the effect separately
  276. if(my_divisor) src.my_max_depth += static_cast<depth_t>(__TBB_Log2(src.my_divisor/my_divisor));
  277. #endif
  278. }
  279. bool check_being_stolen( task &t) { // part of old should_execute_range()
  280. if( !my_divisor ) { // if not from the top P tasks of binary tree
  281. my_divisor = 1; // TODO: replace by on-stack flag (partition_state's member)?
  282. if( t.is_stolen_task() ) {
  283. #if TBB_USE_EXCEPTIONS
  284. // RTTI is available, check whether the cast is valid
  285. __TBB_ASSERT(dynamic_cast<flag_task*>(t.parent()), 0);
  286. // correctness of the cast relies on avoiding the root task for which:
  287. // - initial value of my_divisor != 0 (protected by separate assertion)
  288. // - is_stolen_task() always returns false for the root task.
  289. #endif
  290. flag_task::mark_task_stolen(t);
  291. my_max_depth++;
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. bool divisions_left() { // part of old should_execute_range()
  298. if( my_divisor > 1 ) return true;
  299. if( my_divisor && my_max_depth > 1 ) { // can split the task and once more internally. TODO: on-stack flag instead
  300. // keep same fragmentation while splitting for the local task pool
  301. my_max_depth--;
  302. my_divisor = 0; // decrease max_depth once per task
  303. return true;
  304. } else return false;
  305. }
  306. bool should_create_trap() {
  307. return my_divisor > 0;
  308. }
  309. bool check_for_demand(task &t) {
  310. if( flag_task::is_peer_stolen(t) ) {
  311. my_max_depth++;
  312. return true;
  313. } else return false;
  314. }
  315. void align_depth(depth_t base) {
  316. __TBB_ASSERT(base <= my_max_depth, 0);
  317. my_max_depth -= base;
  318. }
  319. depth_t max_depth() { return my_max_depth; }
  320. };
  321. //! Provides default methods for affinity (adaptive) partition objects.
  322. class affinity_partition_type : public auto_partition_type_base<affinity_partition_type> {
  323. static const unsigned factor_power = 4;
  324. static const unsigned factor = 1<<factor_power;
  325. bool my_delay;
  326. unsigned map_begin, map_end, map_mid;
  327. tbb::internal::affinity_id* my_array;
  328. void set_mid() {
  329. unsigned d = (map_end - map_begin)/2; // we could add 1 but it is rather for LIFO affinity
  330. if( d > factor )
  331. d &= 0u-factor;
  332. map_mid = map_end - d;
  333. }
  334. public:
  335. affinity_partition_type( tbb::internal::affinity_partitioner_base_v3& ap ) {
  336. __TBB_ASSERT( (factor&(factor-1))==0, "factor must be power of two" );
  337. ap.resize(factor);
  338. my_array = ap.my_array;
  339. map_begin = 0;
  340. map_end = unsigned(ap.my_size);
  341. set_mid();
  342. my_delay = true;
  343. my_divisor /= __TBB_INITIAL_CHUNKS; // let exactly P tasks to be distributed across workers
  344. my_max_depth = factor_power+1; // the first factor_power ranges will be spawned, and >=1 ranges should be left
  345. __TBB_ASSERT( my_max_depth < __TBB_RANGE_POOL_CAPACITY, 0 );
  346. }
  347. affinity_partition_type(affinity_partition_type& p, split)
  348. : auto_partition_type_base<affinity_partition_type>(p, split()), my_array(p.my_array) {
  349. __TBB_ASSERT( p.map_end-p.map_begin<factor || (p.map_end-p.map_begin)%factor==0, NULL );
  350. map_end = p.map_end;
  351. map_begin = p.map_end = p.map_mid;
  352. set_mid(); p.set_mid();
  353. my_delay = p.my_delay;
  354. }
  355. void set_affinity( task &t ) {
  356. if( map_begin<map_end )
  357. t.set_affinity( my_array[map_begin] );
  358. }
  359. void note_affinity( task::affinity_id id ) {
  360. if( map_begin<map_end )
  361. my_array[map_begin] = id;
  362. }
  363. bool check_for_demand( task &t ) {
  364. if( !my_delay ) {
  365. if( map_mid<map_end ) {
  366. __TBB_ASSERT(my_max_depth>__TBB_Log2(map_end-map_mid), 0);
  367. return true;// do not do my_max_depth++ here, but be sure my_max_depth is big enough
  368. }
  369. if( flag_task::is_peer_stolen(t) ) {
  370. my_max_depth++;
  371. return true;
  372. }
  373. } else my_delay = false;
  374. return false;
  375. }
  376. bool divisions_left() { // part of old should_execute_range()
  377. return my_divisor > 1;
  378. }
  379. bool should_create_trap() {
  380. return true; // TODO: rethink for the stage after memorizing level
  381. }
  382. static const unsigned range_pool_size = __TBB_RANGE_POOL_CAPACITY;
  383. };
  384. class auto_partition_type: public auto_partition_type_base<auto_partition_type> {
  385. public:
  386. auto_partition_type( const auto_partitioner& ) {}
  387. auto_partition_type( auto_partition_type& src, split)
  388. : auto_partition_type_base<auto_partition_type>(src, split()) {}
  389. static const unsigned range_pool_size = __TBB_RANGE_POOL_CAPACITY;
  390. };
  391. class simple_partition_type: public partition_type_base<simple_partition_type> {
  392. public:
  393. simple_partition_type( const simple_partitioner& ) {}
  394. simple_partition_type( const simple_partition_type&, split ) {}
  395. //! simplified algorithm
  396. template<typename StartType, typename Range>
  397. void execute(StartType &start, Range &range) {
  398. while( range.is_divisible() )
  399. split_work( start );
  400. start.run_body( range );
  401. }
  402. //static const unsigned range_pool_size = 1; - not necessary because execute() is overridden
  403. };
  404. //! Backward-compatible partition for auto and affinity partition objects.
  405. class old_auto_partition_type: public tbb::internal::partition_type_base {
  406. size_t num_chunks;
  407. static const size_t VICTIM_CHUNKS = 4;
  408. public:
  409. bool should_execute_range(const task &t) {
  410. if( num_chunks<VICTIM_CHUNKS && t.is_stolen_task() )
  411. num_chunks = VICTIM_CHUNKS;
  412. return num_chunks==1;
  413. }
  414. old_auto_partition_type( const auto_partitioner& )
  415. : num_chunks(internal::get_initial_auto_partitioner_divisor()*__TBB_INITIAL_CHUNKS/4) {}
  416. old_auto_partition_type( const affinity_partitioner& )
  417. : num_chunks(internal::get_initial_auto_partitioner_divisor()*__TBB_INITIAL_CHUNKS/4) {}
  418. old_auto_partition_type( old_auto_partition_type& pt, split ) {
  419. num_chunks = pt.num_chunks = (pt.num_chunks+1u) / 2u;
  420. }
  421. };
  422. } // namespace interfaceX::internal
  423. //! @endcond
  424. } // namespace interfaceX
  425. //! A simple partitioner
  426. /** Divides the range until the range is not divisible.
  427. @ingroup algorithms */
  428. class simple_partitioner {
  429. public:
  430. simple_partitioner() {}
  431. private:
  432. template<typename Range, typename Body, typename Partitioner> friend class serial::interface6::start_for;
  433. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_for;
  434. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_reduce;
  435. template<typename Range, typename Body, typename Partitioner> friend class internal::start_scan;
  436. // backward compatibility
  437. class partition_type: public internal::partition_type_base {
  438. public:
  439. bool should_execute_range(const task& ) {return false;}
  440. partition_type( const simple_partitioner& ) {}
  441. partition_type( const partition_type&, split ) {}
  442. };
  443. // new implementation just extends existing interface
  444. typedef interface6::internal::simple_partition_type task_partition_type;
  445. };
  446. //! An auto partitioner
  447. /** The range is initial divided into several large chunks.
  448. Chunks are further subdivided into smaller pieces if demand detected and they are divisible.
  449. @ingroup algorithms */
  450. class auto_partitioner {
  451. public:
  452. auto_partitioner() {}
  453. private:
  454. template<typename Range, typename Body, typename Partitioner> friend class serial::interface6::start_for;
  455. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_for;
  456. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_reduce;
  457. template<typename Range, typename Body, typename Partitioner> friend class internal::start_scan;
  458. // backward compatibility
  459. typedef interface6::internal::old_auto_partition_type partition_type;
  460. // new implementation just extends existing interface
  461. typedef interface6::internal::auto_partition_type task_partition_type;
  462. };
  463. //! An affinity partitioner
  464. class affinity_partitioner: internal::affinity_partitioner_base_v3 {
  465. public:
  466. affinity_partitioner() {}
  467. private:
  468. template<typename Range, typename Body, typename Partitioner> friend class serial::interface6::start_for;
  469. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_for;
  470. template<typename Range, typename Body, typename Partitioner> friend class interface6::internal::start_reduce;
  471. template<typename Range, typename Body, typename Partitioner> friend class internal::start_scan;
  472. // backward compatibility - for parallel_scan only
  473. typedef interface6::internal::old_auto_partition_type partition_type;
  474. // new implementation just extends existing interface
  475. typedef interface6::internal::affinity_partition_type task_partition_type;
  476. };
  477. } // namespace tbb
  478. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  479. #pragma warning (pop)
  480. #endif // warning 4244 is back
  481. #undef __TBB_INITIAL_CHUNKS
  482. #undef __TBB_RANGE_POOL_CAPACITY
  483. #undef __TBB_INIT_DEPTH
  484. #endif /* __TBB_partitioner_H */