Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

313 lines
9.4KB

  1. // -*- C++ -*-
  2. // Copyright (C) 2007-2020 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the terms
  6. // of the GNU General Public License as published by the Free Software
  7. // Foundation; either version 3, or (at your option) any later
  8. // version.
  9. // This library is distributed in the hope that it will be useful, but
  10. // WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. // General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file parallel/workstealing.h
  21. * @brief Parallelization of embarrassingly parallel execution by
  22. * means of work-stealing.
  23. *
  24. * Work stealing is described in
  25. *
  26. * R. D. Blumofe and C. E. Leiserson.
  27. * Scheduling multithreaded computations by work stealing.
  28. * Journal of the ACM, 46(5):720-748, 1999.
  29. *
  30. * This file is a GNU parallel extension to the Standard C++ Library.
  31. */
  32. // Written by Felix Putze.
  33. #ifndef _GLIBCXX_PARALLEL_WORKSTEALING_H
  34. #define _GLIBCXX_PARALLEL_WORKSTEALING_H 1
  35. #include <parallel/parallel.h>
  36. #include <parallel/random_number.h>
  37. #include <parallel/compatibility.h>
  38. namespace __gnu_parallel
  39. {
  40. #define _GLIBCXX_JOB_VOLATILE volatile
  41. /** @brief One __job for a certain thread. */
  42. template<typename _DifferenceTp>
  43. struct _Job
  44. {
  45. typedef _DifferenceTp _DifferenceType;
  46. /** @brief First element.
  47. *
  48. * Changed by owning and stealing thread. By stealing thread,
  49. * always incremented. */
  50. _GLIBCXX_JOB_VOLATILE _DifferenceType _M_first;
  51. /** @brief Last element.
  52. *
  53. * Changed by owning thread only. */
  54. _GLIBCXX_JOB_VOLATILE _DifferenceType _M_last;
  55. /** @brief Number of elements, i.e. @c _M_last-_M_first+1.
  56. *
  57. * Changed by owning thread only. */
  58. _GLIBCXX_JOB_VOLATILE _DifferenceType _M_load;
  59. };
  60. /** @brief Work stealing algorithm for random access iterators.
  61. *
  62. * Uses O(1) additional memory. Synchronization at job lists is
  63. * done with atomic operations.
  64. * @param __begin Begin iterator of element sequence.
  65. * @param __end End iterator of element sequence.
  66. * @param __op User-supplied functor (comparator, predicate, adding
  67. * functor, ...).
  68. * @param __f Functor to @a process an element with __op (depends on
  69. * desired functionality, e. g. for std::for_each(), ...).
  70. * @param __r Functor to @a add a single __result to the already
  71. * processed elements (depends on functionality).
  72. * @param __base Base value for reduction.
  73. * @param __output Pointer to position where final result is written to
  74. * @param __bound Maximum number of elements processed (e. g. for
  75. * std::count_n()).
  76. * @return User-supplied functor (that may contain a part of the result).
  77. */
  78. template<typename _RAIter,
  79. typename _Op,
  80. typename _Fu,
  81. typename _Red,
  82. typename _Result>
  83. _Op
  84. __for_each_template_random_access_workstealing(_RAIter __begin,
  85. _RAIter __end, _Op __op,
  86. _Fu& __f, _Red __r,
  87. _Result __base,
  88. _Result& __output,
  89. typename std::iterator_traits<_RAIter>::difference_type __bound)
  90. {
  91. _GLIBCXX_CALL(__end - __begin)
  92. typedef std::iterator_traits<_RAIter> _TraitsType;
  93. typedef typename _TraitsType::difference_type _DifferenceType;
  94. const _Settings& __s = _Settings::get();
  95. _DifferenceType __chunk_size =
  96. static_cast<_DifferenceType>(__s.workstealing_chunk_size);
  97. // How many jobs?
  98. _DifferenceType __length = (__bound < 0) ? (__end - __begin) : __bound;
  99. // To avoid false sharing in a cache line.
  100. const int __stride = (__s.cache_line_size * 10
  101. / sizeof(_Job<_DifferenceType>) + 1);
  102. // Total number of threads currently working.
  103. _ThreadIndex __busy = 0;
  104. _Job<_DifferenceType> *__job;
  105. omp_lock_t __output_lock;
  106. omp_init_lock(&__output_lock);
  107. // Write base value to output.
  108. __output = __base;
  109. // No more threads than jobs, at least one thread.
  110. _ThreadIndex __num_threads = __gnu_parallel::max<_ThreadIndex>
  111. (1, __gnu_parallel::min<_DifferenceType>(__length,
  112. __get_max_threads()));
  113. # pragma omp parallel shared(__busy) num_threads(__num_threads)
  114. {
  115. # pragma omp single
  116. {
  117. __num_threads = omp_get_num_threads();
  118. // Create job description array.
  119. __job = new _Job<_DifferenceType>[__num_threads * __stride];
  120. }
  121. // Initialization phase.
  122. // Flags for every thread if it is doing productive work.
  123. bool __iam_working = false;
  124. // Thread id.
  125. _ThreadIndex __iam = omp_get_thread_num();
  126. // This job.
  127. _Job<_DifferenceType>& __my_job = __job[__iam * __stride];
  128. // Random number (for work stealing).
  129. _ThreadIndex __victim;
  130. // Local value for reduction.
  131. _Result __result = _Result();
  132. // Number of elements to steal in one attempt.
  133. _DifferenceType __steal;
  134. // Every thread has its own random number generator
  135. // (modulo __num_threads).
  136. _RandomNumber __rand_gen(__iam, __num_threads);
  137. // This thread is currently working.
  138. # pragma omp atomic
  139. ++__busy;
  140. __iam_working = true;
  141. // How many jobs per thread? last thread gets the rest.
  142. __my_job._M_first = static_cast<_DifferenceType>
  143. (__iam * (__length / __num_threads));
  144. __my_job._M_last = (__iam == (__num_threads - 1)
  145. ? (__length - 1)
  146. : ((__iam + 1) * (__length / __num_threads) - 1));
  147. __my_job._M_load = __my_job._M_last - __my_job._M_first + 1;
  148. // Init result with _M_first value (to have a base value for reduction)
  149. if (__my_job._M_first <= __my_job._M_last)
  150. {
  151. // Cannot use volatile variable directly.
  152. _DifferenceType __my_first = __my_job._M_first;
  153. __result = __f(__op, __begin + __my_first);
  154. ++__my_job._M_first;
  155. --__my_job._M_load;
  156. }
  157. _RAIter __current;
  158. # pragma omp barrier
  159. // Actual work phase
  160. // Work on own or stolen current start
  161. while (__busy > 0)
  162. {
  163. // Work until no productive thread left.
  164. # pragma omp flush(__busy)
  165. // Thread has own work to do
  166. while (__my_job._M_first <= __my_job._M_last)
  167. {
  168. // fetch-and-add call
  169. // Reserve current job block (size __chunk_size) in my queue.
  170. _DifferenceType __current_job =
  171. __fetch_and_add<_DifferenceType>(&(__my_job._M_first),
  172. __chunk_size);
  173. // Update _M_load, to make the three values consistent,
  174. // _M_first might have been changed in the meantime
  175. __my_job._M_load = __my_job._M_last - __my_job._M_first + 1;
  176. for (_DifferenceType __job_counter = 0;
  177. __job_counter < __chunk_size
  178. && __current_job <= __my_job._M_last;
  179. ++__job_counter)
  180. {
  181. // Yes: process it!
  182. __current = __begin + __current_job;
  183. ++__current_job;
  184. // Do actual work.
  185. __result = __r(__result, __f(__op, __current));
  186. }
  187. # pragma omp flush(__busy)
  188. }
  189. // After reaching this point, a thread's __job list is empty.
  190. if (__iam_working)
  191. {
  192. // This thread no longer has work.
  193. # pragma omp atomic
  194. --__busy;
  195. __iam_working = false;
  196. }
  197. _DifferenceType __supposed_first, __supposed_last,
  198. __supposed_load;
  199. do
  200. {
  201. // Find random nonempty deque (not own), do consistency check.
  202. __yield();
  203. # pragma omp flush(__busy)
  204. __victim = __rand_gen();
  205. __supposed_first = __job[__victim * __stride]._M_first;
  206. __supposed_last = __job[__victim * __stride]._M_last;
  207. __supposed_load = __job[__victim * __stride]._M_load;
  208. }
  209. while (__busy > 0
  210. && ((__supposed_load <= 0)
  211. || ((__supposed_first + __supposed_load - 1)
  212. != __supposed_last)));
  213. if (__busy == 0)
  214. break;
  215. if (__supposed_load > 0)
  216. {
  217. // Has work and work to do.
  218. // Number of elements to steal (at least one).
  219. __steal = (__supposed_load < 2) ? 1 : __supposed_load / 2;
  220. // Push __victim's current start forward.
  221. _DifferenceType __stolen_first =
  222. __fetch_and_add<_DifferenceType>
  223. (&(__job[__victim * __stride]._M_first), __steal);
  224. _DifferenceType __stolen_try = (__stolen_first + __steal
  225. - _DifferenceType(1));
  226. __my_job._M_first = __stolen_first;
  227. __my_job._M_last = __gnu_parallel::min(__stolen_try,
  228. __supposed_last);
  229. __my_job._M_load = __my_job._M_last - __my_job._M_first + 1;
  230. // Has potential work again.
  231. # pragma omp atomic
  232. ++__busy;
  233. __iam_working = true;
  234. # pragma omp flush(__busy)
  235. }
  236. # pragma omp flush(__busy)
  237. } // end while __busy > 0
  238. // Add accumulated result to output.
  239. omp_set_lock(&__output_lock);
  240. __output = __r(__output, __result);
  241. omp_unset_lock(&__output_lock);
  242. }
  243. delete[] __job;
  244. // Points to last element processed (needed as return value for
  245. // some algorithms like transform)
  246. __f._M_finish_iterator = __begin + __length;
  247. omp_destroy_lock(&__output_lock);
  248. return __op;
  249. }
  250. } // end namespace
  251. #endif /* _GLIBCXX_PARALLEL_WORKSTEALING_H */