task.h 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. /*
  2. Copyright 2005-2015 Intel Corporation. All Rights Reserved.
  3. This file is part of Threading Building Blocks. Threading Building Blocks is free software;
  4. you can redistribute it and/or modify it under the terms of the GNU General Public License
  5. version 2 as published by the Free Software Foundation. Threading Building Blocks is
  6. distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the GNU General Public License for more details. You should have received a copy of
  9. the GNU General Public License along with Threading Building Blocks; if not, write to the
  10. Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  11. As a special exception, you may use this file as part of a free software library without
  12. restriction. Specifically, if other files instantiate templates or use macros or inline
  13. functions from this file, or you compile this file and link it with other files to produce
  14. an executable, this file does not by itself cause the resulting executable to be covered
  15. by the GNU General Public License. This exception does not however invalidate any other
  16. reasons why the executable file might be covered by the GNU General Public License.
  17. */
  18. #ifndef __TBB_task_H
  19. #define __TBB_task_H
  20. #include "tbb_stddef.h"
  21. #include "tbb_machine.h"
  22. #include "tbb_profiling.h"
  23. #include <climits>
  24. typedef struct ___itt_caller *__itt_caller;
  25. namespace tbb {
  26. class task;
  27. class task_list;
  28. class task_group_context;
  29. // MSVC does not allow taking the address of a member that was defined
  30. // privately in task_base and made public in class task via a using declaration.
  31. #if _MSC_VER || (__GNUC__==3 && __GNUC_MINOR__<3)
  32. #define __TBB_TASK_BASE_ACCESS public
  33. #else
  34. #define __TBB_TASK_BASE_ACCESS private
  35. #endif
  36. namespace internal { //< @cond INTERNAL
  37. class allocate_additional_child_of_proxy: no_assign {
  38. //! No longer used, but retained for binary layout compatibility. Always NULL.
  39. task* self;
  40. task& parent;
  41. public:
  42. explicit allocate_additional_child_of_proxy( task& parent_ ) : self(NULL), parent(parent_) {}
  43. task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
  44. void __TBB_EXPORTED_METHOD free( task& ) const;
  45. };
  46. struct cpu_ctl_env_space { int space[sizeof(internal::uint64_t)/sizeof(int)]; };
  47. } //< namespace internal @endcond
  48. namespace interface5 {
  49. namespace internal {
  50. //! Base class for methods that became static in TBB 3.0.
  51. /** TBB's evolution caused the "this" argument for several methods to become obsolete.
  52. However, for backwards binary compatibility, the new methods need distinct names,
  53. otherwise the One Definition Rule would be broken. Hence the new methods are
  54. defined in this private base class, and then exposed in class task via
  55. using declarations. */
  56. class task_base: tbb::internal::no_copy {
  57. __TBB_TASK_BASE_ACCESS:
  58. friend class tbb::task;
  59. //! Schedule task for execution when a worker becomes available.
  60. static void spawn( task& t );
  61. //! Spawn multiple tasks and clear list.
  62. static void spawn( task_list& list );
  63. //! Like allocate_child, except that task's parent becomes "t", not this.
  64. /** Typically used in conjunction with schedule_to_reexecute to implement while loops.
  65. Atomically increments the reference count of t.parent() */
  66. static tbb::internal::allocate_additional_child_of_proxy allocate_additional_child_of( task& t ) {
  67. return tbb::internal::allocate_additional_child_of_proxy(t);
  68. }
  69. //! Destroy a task.
  70. /** Usually, calling this method is unnecessary, because a task is
  71. implicitly deleted after its execute() method runs. However,
  72. sometimes a task needs to be explicitly deallocated, such as
  73. when a root task is used as the parent in spawn_and_wait_for_all. */
  74. static void __TBB_EXPORTED_FUNC destroy( task& victim );
  75. };
  76. } // internal
  77. } // interface5
  78. //! @cond INTERNAL
  79. namespace internal {
  80. class scheduler: no_copy {
  81. public:
  82. //! For internal use only
  83. virtual void spawn( task& first, task*& next ) = 0;
  84. //! For internal use only
  85. virtual void wait_for_all( task& parent, task* child ) = 0;
  86. //! For internal use only
  87. virtual void spawn_root_and_wait( task& first, task*& next ) = 0;
  88. //! Pure virtual destructor;
  89. // Have to have it just to shut up overzealous compilation warnings
  90. virtual ~scheduler() = 0;
  91. //! For internal use only
  92. virtual void enqueue( task& t, void* reserved ) = 0;
  93. };
  94. //! A reference count
  95. /** Should always be non-negative. A signed type is used so that underflow can be detected. */
  96. typedef intptr_t reference_count;
  97. //! An id as used for specifying affinity.
  98. typedef unsigned short affinity_id;
  99. #if __TBB_TASK_GROUP_CONTEXT
  100. class generic_scheduler;
  101. struct context_list_node_t {
  102. context_list_node_t *my_prev,
  103. *my_next;
  104. };
  105. class allocate_root_with_context_proxy: no_assign {
  106. task_group_context& my_context;
  107. public:
  108. allocate_root_with_context_proxy ( task_group_context& ctx ) : my_context(ctx) {}
  109. task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
  110. void __TBB_EXPORTED_METHOD free( task& ) const;
  111. };
  112. #endif /* __TBB_TASK_GROUP_CONTEXT */
  113. class allocate_root_proxy: no_assign {
  114. public:
  115. static task& __TBB_EXPORTED_FUNC allocate( size_t size );
  116. static void __TBB_EXPORTED_FUNC free( task& );
  117. };
  118. class allocate_continuation_proxy: no_assign {
  119. public:
  120. task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
  121. void __TBB_EXPORTED_METHOD free( task& ) const;
  122. };
  123. class allocate_child_proxy: no_assign {
  124. public:
  125. task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
  126. void __TBB_EXPORTED_METHOD free( task& ) const;
  127. };
  128. //! Memory prefix to a task object.
  129. /** This class is internal to the library.
  130. Do not reference it directly, except within the library itself.
  131. Fields are ordered in way that preserves backwards compatibility and yields
  132. good packing on typical 32-bit and 64-bit platforms.
  133. In case task prefix size exceeds 32 or 64 bytes on IA32 and Intel64
  134. architectures correspondingly, consider dynamic setting of task_alignment
  135. and task_prefix_reservation_size based on the maximal operand size supported
  136. by the current CPU.
  137. @ingroup task_scheduling */
  138. class task_prefix {
  139. private:
  140. friend class tbb::task;
  141. friend class tbb::interface5::internal::task_base;
  142. friend class tbb::task_list;
  143. friend class internal::scheduler;
  144. friend class internal::allocate_root_proxy;
  145. friend class internal::allocate_child_proxy;
  146. friend class internal::allocate_continuation_proxy;
  147. friend class internal::allocate_additional_child_of_proxy;
  148. #if __TBB_TASK_GROUP_CONTEXT
  149. //! Shared context that is used to communicate asynchronous state changes
  150. /** Currently it is used to broadcast cancellation requests generated both
  151. by users and as the result of unhandled exceptions in the task::execute()
  152. methods. */
  153. task_group_context *context;
  154. #endif /* __TBB_TASK_GROUP_CONTEXT */
  155. //! The scheduler that allocated the task, or NULL if the task is big.
  156. /** Small tasks are pooled by the scheduler that allocated the task.
  157. If a scheduler needs to free a small task allocated by another scheduler,
  158. it returns the task to that other scheduler. This policy avoids
  159. memory space blowup issues for memory allocators that allocate from
  160. thread-specific pools. */
  161. scheduler* origin;
  162. #if __TBB_TASK_PRIORITY
  163. union {
  164. #endif /* __TBB_TASK_PRIORITY */
  165. //! Obsolete. The scheduler that owns the task.
  166. /** Retained only for the sake of backward binary compatibility.
  167. Still used by inline methods in the task.h header. **/
  168. scheduler* owner;
  169. #if __TBB_TASK_PRIORITY
  170. //! Pointer to the next offloaded lower priority task.
  171. /** Used to maintain a list of offloaded tasks inside the scheduler. **/
  172. task* next_offloaded;
  173. };
  174. #endif /* __TBB_TASK_PRIORITY */
  175. //! The task whose reference count includes me.
  176. /** In the "blocking style" of programming, this field points to the parent task.
  177. In the "continuation-passing style" of programming, this field points to the
  178. continuation of the parent. */
  179. tbb::task* parent;
  180. //! Reference count used for synchronization.
  181. /** In the "continuation-passing style" of programming, this field is
  182. the difference of the number of allocated children minus the
  183. number of children that have completed.
  184. In the "blocking style" of programming, this field is one more than the difference. */
  185. __TBB_atomic reference_count ref_count;
  186. //! Obsolete. Used to be scheduling depth before TBB 2.2
  187. /** Retained only for the sake of backward binary compatibility.
  188. Not used by TBB anymore. **/
  189. int depth;
  190. //! A task::state_type, stored as a byte for compactness.
  191. /** This state is exposed to users via method task::state(). */
  192. unsigned char state;
  193. //! Miscellaneous state that is not directly visible to users, stored as a byte for compactness.
  194. /** 0x0 -> version 1.0 task
  195. 0x1 -> version >=2.1 task
  196. 0x10 -> task was enqueued
  197. 0x20 -> task_proxy
  198. 0x40 -> task has live ref_count
  199. 0x80 -> a stolen task */
  200. unsigned char extra_state;
  201. affinity_id affinity;
  202. //! "next" field for list of task
  203. tbb::task* next;
  204. //! The task corresponding to this task_prefix.
  205. tbb::task& task() {return *reinterpret_cast<tbb::task*>(this+1);}
  206. };
  207. } // namespace internal
  208. //! @endcond
  209. #if __TBB_TASK_GROUP_CONTEXT
  210. #if __TBB_TASK_PRIORITY
  211. namespace internal {
  212. static const int priority_stride_v4 = INT_MAX / 4;
  213. }
  214. enum priority_t {
  215. priority_normal = internal::priority_stride_v4 * 2,
  216. priority_low = priority_normal - internal::priority_stride_v4,
  217. priority_high = priority_normal + internal::priority_stride_v4
  218. };
  219. #endif /* __TBB_TASK_PRIORITY */
  220. #if TBB_USE_CAPTURED_EXCEPTION
  221. class tbb_exception;
  222. #else
  223. namespace internal {
  224. class tbb_exception_ptr;
  225. }
  226. #endif /* !TBB_USE_CAPTURED_EXCEPTION */
  227. class task_scheduler_init;
  228. namespace interface7 { class task_arena; }
  229. //! Used to form groups of tasks
  230. /** @ingroup task_scheduling
  231. The context services explicit cancellation requests from user code, and unhandled
  232. exceptions intercepted during tasks execution. Intercepting an exception results
  233. in generating internal cancellation requests (which is processed in exactly the
  234. same way as external ones).
  235. The context is associated with one or more root tasks and defines the cancellation
  236. group that includes all the descendants of the corresponding root task(s). Association
  237. is established when a context object is passed as an argument to the task::allocate_root()
  238. method. See task_group_context::task_group_context for more details.
  239. The context can be bound to another one, and other contexts can be bound to it,
  240. forming a tree-like structure: parent -> this -> children. Arrows here designate
  241. cancellation propagation direction. If a task in a cancellation group is cancelled
  242. all the other tasks in this group and groups bound to it (as children) get cancelled too.
  243. IMPLEMENTATION NOTE:
  244. When adding new members to task_group_context or changing types of existing ones,
  245. update the size of both padding buffers (_leading_padding and _trailing_padding)
  246. appropriately. See also VERSIONING NOTE at the constructor definition below. **/
  247. class task_group_context : internal::no_copy {
  248. private:
  249. friend class internal::generic_scheduler;
  250. friend class task_scheduler_init;
  251. friend class interface7::task_arena;
  252. #if TBB_USE_CAPTURED_EXCEPTION
  253. typedef tbb_exception exception_container_type;
  254. #else
  255. typedef internal::tbb_exception_ptr exception_container_type;
  256. #endif
  257. enum version_traits_word_layout {
  258. traits_offset = 16,
  259. version_mask = 0xFFFF,
  260. traits_mask = 0xFFFFul << traits_offset
  261. };
  262. public:
  263. enum kind_type {
  264. isolated,
  265. bound
  266. };
  267. enum traits_type {
  268. exact_exception = 0x0001ul << traits_offset,
  269. #if __TBB_FP_CONTEXT
  270. fp_settings = 0x0002ul << traits_offset,
  271. #endif
  272. concurrent_wait = 0x0004ul << traits_offset,
  273. #if TBB_USE_CAPTURED_EXCEPTION
  274. default_traits = 0
  275. #else
  276. default_traits = exact_exception
  277. #endif /* !TBB_USE_CAPTURED_EXCEPTION */
  278. };
  279. private:
  280. enum state {
  281. may_have_children = 1,
  282. // the following enumerations must be the last, new 2^x values must go above
  283. next_state_value, low_unused_state_bit = (next_state_value-1)*2
  284. };
  285. union {
  286. //! Flavor of this context: bound or isolated.
  287. // TODO: describe asynchronous use, and whether any memory semantics are needed
  288. __TBB_atomic kind_type my_kind;
  289. uintptr_t _my_kind_aligner;
  290. };
  291. //! Pointer to the context of the parent cancellation group. NULL for isolated contexts.
  292. task_group_context *my_parent;
  293. //! Used to form the thread specific list of contexts without additional memory allocation.
  294. /** A context is included into the list of the current thread when its binding to
  295. its parent happens. Any context can be present in the list of one thread only. **/
  296. internal::context_list_node_t my_node;
  297. //! Used to set and maintain stack stitching point for Intel Performance Tools.
  298. __itt_caller itt_caller;
  299. //! Leading padding protecting accesses to frequently used members from false sharing.
  300. /** Read accesses to the field my_cancellation_requested are on the hot path inside
  301. the scheduler. This padding ensures that this field never shares the same cache
  302. line with a local variable that is frequently written to. **/
  303. char _leading_padding[internal::NFS_MaxLineSize
  304. - 2 * sizeof(uintptr_t)- sizeof(void*) - sizeof(internal::context_list_node_t)
  305. - sizeof(__itt_caller)
  306. #if __TBB_FP_CONTEXT
  307. - sizeof(internal::cpu_ctl_env_space)
  308. #endif
  309. ];
  310. #if __TBB_FP_CONTEXT
  311. //! Space for platform-specific FPU settings.
  312. /** Must only be accessed inside TBB binaries, and never directly in user
  313. code or inline methods. */
  314. internal::cpu_ctl_env_space my_cpu_ctl_env;
  315. #endif
  316. //! Specifies whether cancellation was requested for this task group.
  317. uintptr_t my_cancellation_requested;
  318. //! Version for run-time checks and behavioral traits of the context.
  319. /** Version occupies low 16 bits, and traits (zero or more ORed enumerators
  320. from the traits_type enumerations) take the next 16 bits.
  321. Original (zeroth) version of the context did not support any traits. **/
  322. uintptr_t my_version_and_traits;
  323. //! Pointer to the container storing exception being propagated across this task group.
  324. exception_container_type *my_exception;
  325. //! Scheduler instance that registered this context in its thread specific list.
  326. internal::generic_scheduler *my_owner;
  327. //! Internal state (combination of state flags, currently only may_have_children).
  328. uintptr_t my_state;
  329. #if __TBB_TASK_PRIORITY
  330. //! Priority level of the task group (in normalized representation)
  331. intptr_t my_priority;
  332. #endif /* __TBB_TASK_PRIORITY */
  333. //! Trailing padding protecting accesses to frequently used members from false sharing
  334. /** \sa _leading_padding **/
  335. char _trailing_padding[internal::NFS_MaxLineSize - 2 * sizeof(uintptr_t) - 2 * sizeof(void*)
  336. #if __TBB_TASK_PRIORITY
  337. - sizeof(intptr_t)
  338. #endif /* __TBB_TASK_PRIORITY */
  339. ];
  340. public:
  341. //! Default & binding constructor.
  342. /** By default a bound context is created. That is this context will be bound
  343. (as child) to the context of the task calling task::allocate_root(this_context)
  344. method. Cancellation requests passed to the parent context are propagated
  345. to all the contexts bound to it. Similarly priority change is propagated
  346. from the parent context to its children.
  347. If task_group_context::isolated is used as the argument, then the tasks associated
  348. with this context will never be affected by events in any other context.
  349. Creating isolated contexts involve much less overhead, but they have limited
  350. utility. Normally when an exception occurs in an algorithm that has nested
  351. ones running, it is desirably to have all the nested algorithms cancelled
  352. as well. Such a behavior requires nested algorithms to use bound contexts.
  353. There is one good place where using isolated algorithms is beneficial. It is
  354. a master thread. That is if a particular algorithm is invoked directly from
  355. the master thread (not from a TBB task), supplying it with explicitly
  356. created isolated context will result in a faster algorithm startup.
  357. VERSIONING NOTE:
  358. Implementation(s) of task_group_context constructor(s) cannot be made
  359. entirely out-of-line because the run-time version must be set by the user
  360. code. This will become critically important for binary compatibility, if
  361. we ever have to change the size of the context object.
  362. Boosting the runtime version will also be necessary if new data fields are
  363. introduced in the currently unused padding areas and these fields are updated
  364. by inline methods. **/
  365. task_group_context ( kind_type relation_with_parent = bound,
  366. uintptr_t traits = default_traits )
  367. : my_kind(relation_with_parent)
  368. , my_version_and_traits(2 | traits)
  369. {
  370. init();
  371. }
  372. // Do not introduce standalone unbind method since it will break state propagation assumptions
  373. __TBB_EXPORTED_METHOD ~task_group_context ();
  374. //! Forcefully reinitializes the context after the task tree it was associated with is completed.
  375. /** Because the method assumes that all the tasks that used to be associated with
  376. this context have already finished, calling it while the context is still
  377. in use somewhere in the task hierarchy leads to undefined behavior.
  378. IMPORTANT: This method is not thread safe!
  379. The method does not change the context's parent if it is set. **/
  380. void __TBB_EXPORTED_METHOD reset ();
  381. //! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
  382. /** \return false if cancellation has already been requested, true otherwise.
  383. Note that canceling never fails. When false is returned, it just means that
  384. another thread (or this one) has already sent cancellation request to this
  385. context or to one of its ancestors (if this context is bound). It is guaranteed
  386. that when this method is concurrently called on the same not yet cancelled
  387. context, true will be returned by one and only one invocation. **/
  388. bool __TBB_EXPORTED_METHOD cancel_group_execution ();
  389. //! Returns true if the context received cancellation request.
  390. bool __TBB_EXPORTED_METHOD is_group_execution_cancelled () const;
  391. //! Records the pending exception, and cancels the task group.
  392. /** May be called only from inside a catch-block. If the context is already
  393. cancelled, does nothing.
  394. The method brings the task group associated with this context exactly into
  395. the state it would be in, if one of its tasks threw the currently pending
  396. exception during its execution. In other words, it emulates the actions
  397. of the scheduler's dispatch loop exception handler. **/
  398. void __TBB_EXPORTED_METHOD register_pending_exception ();
  399. #if __TBB_FP_CONTEXT
  400. //! Captures the current FPU control settings to the context.
  401. /** Because the method assumes that all the tasks that used to be associated with
  402. this context have already finished, calling it while the context is still
  403. in use somewhere in the task hierarchy leads to undefined behavior.
  404. IMPORTANT: This method is not thread safe!
  405. The method does not change the FPU control settings of the context's parent. **/
  406. void __TBB_EXPORTED_METHOD capture_fp_settings ();
  407. #endif
  408. #if __TBB_TASK_PRIORITY
  409. //! Changes priority of the task group
  410. void set_priority ( priority_t );
  411. //! Retrieves current priority of the current task group
  412. priority_t priority () const;
  413. #endif /* __TBB_TASK_PRIORITY */
  414. protected:
  415. //! Out-of-line part of the constructor.
  416. /** Singled out to ensure backward binary compatibility of the future versions. **/
  417. void __TBB_EXPORTED_METHOD init ();
  418. private:
  419. friend class task;
  420. friend class internal::allocate_root_with_context_proxy;
  421. static const kind_type binding_required = bound;
  422. static const kind_type binding_completed = kind_type(bound+1);
  423. static const kind_type detached = kind_type(binding_completed+1);
  424. static const kind_type dying = kind_type(detached+1);
  425. //! Propagates any state change detected to *this, and as an optimisation possibly also upward along the heritage line.
  426. template <typename T>
  427. void propagate_task_group_state ( T task_group_context::*mptr_state, task_group_context& src, T new_state );
  428. //! Registers this context with the local scheduler and binds it to its parent context
  429. void bind_to ( internal::generic_scheduler *local_sched );
  430. //! Registers this context with the local scheduler
  431. void register_with ( internal::generic_scheduler *local_sched );
  432. #if __TBB_FP_CONTEXT
  433. //! Copies FPU control setting from another context
  434. // TODO: Consider adding #else stub in order to omit #if sections in other code
  435. void copy_fp_settings( const task_group_context &src );
  436. #endif /* __TBB_FP_CONTEXT */
  437. }; // class task_group_context
  438. #endif /* __TBB_TASK_GROUP_CONTEXT */
  439. //! Base class for user-defined tasks.
  440. /** @ingroup task_scheduling */
  441. class task: __TBB_TASK_BASE_ACCESS interface5::internal::task_base {
  442. //! Set reference count
  443. void __TBB_EXPORTED_METHOD internal_set_ref_count( int count );
  444. //! Decrement reference count and return its new value.
  445. internal::reference_count __TBB_EXPORTED_METHOD internal_decrement_ref_count();
  446. protected:
  447. //! Default constructor.
  448. task() {prefix().extra_state=1;}
  449. public:
  450. //! Destructor.
  451. virtual ~task() {}
  452. //! Should be overridden by derived classes.
  453. virtual task* execute() = 0;
  454. //! Enumeration of task states that the scheduler considers.
  455. enum state_type {
  456. //! task is running, and will be destroyed after method execute() completes.
  457. executing,
  458. //! task to be rescheduled.
  459. reexecute,
  460. //! task is in ready pool, or is going to be put there, or was just taken off.
  461. ready,
  462. //! task object is freshly allocated or recycled.
  463. allocated,
  464. //! task object is on free list, or is going to be put there, or was just taken off.
  465. freed,
  466. //! task to be recycled as continuation
  467. recycle
  468. #if __TBB_RECYCLE_TO_ENQUEUE
  469. //! task to be scheduled for starvation-resistant execution
  470. ,to_enqueue
  471. #endif
  472. };
  473. //------------------------------------------------------------------------
  474. // Allocating tasks
  475. //------------------------------------------------------------------------
  476. //! Returns proxy for overloaded new that allocates a root task.
  477. static internal::allocate_root_proxy allocate_root() {
  478. return internal::allocate_root_proxy();
  479. }
  480. #if __TBB_TASK_GROUP_CONTEXT
  481. //! Returns proxy for overloaded new that allocates a root task associated with user supplied context.
  482. static internal::allocate_root_with_context_proxy allocate_root( task_group_context& ctx ) {
  483. return internal::allocate_root_with_context_proxy(ctx);
  484. }
  485. #endif /* __TBB_TASK_GROUP_CONTEXT */
  486. //! Returns proxy for overloaded new that allocates a continuation task of *this.
  487. /** The continuation's parent becomes the parent of *this. */
  488. internal::allocate_continuation_proxy& allocate_continuation() {
  489. return *reinterpret_cast<internal::allocate_continuation_proxy*>(this);
  490. }
  491. //! Returns proxy for overloaded new that allocates a child task of *this.
  492. internal::allocate_child_proxy& allocate_child() {
  493. return *reinterpret_cast<internal::allocate_child_proxy*>(this);
  494. }
  495. //! Define recommended static form via import from base class.
  496. using task_base::allocate_additional_child_of;
  497. #if __TBB_DEPRECATED_TASK_INTERFACE
  498. //! Destroy a task.
  499. /** Usually, calling this method is unnecessary, because a task is
  500. implicitly deleted after its execute() method runs. However,
  501. sometimes a task needs to be explicitly deallocated, such as
  502. when a root task is used as the parent in spawn_and_wait_for_all. */
  503. void __TBB_EXPORTED_METHOD destroy( task& t );
  504. #else /* !__TBB_DEPRECATED_TASK_INTERFACE */
  505. //! Define recommended static form via import from base class.
  506. using task_base::destroy;
  507. #endif /* !__TBB_DEPRECATED_TASK_INTERFACE */
  508. //------------------------------------------------------------------------
  509. // Recycling of tasks
  510. //------------------------------------------------------------------------
  511. //! Change this to be a continuation of its former self.
  512. /** The caller must guarantee that the task's refcount does not become zero until
  513. after the method execute() returns. Typically, this is done by having
  514. method execute() return a pointer to a child of the task. If the guarantee
  515. cannot be made, use method recycle_as_safe_continuation instead.
  516. Because of the hazard, this method may be deprecated in the future. */
  517. void recycle_as_continuation() {
  518. __TBB_ASSERT( prefix().state==executing, "execute not running?" );
  519. prefix().state = allocated;
  520. }
  521. //! Recommended to use, safe variant of recycle_as_continuation
  522. /** For safety, it requires additional increment of ref_count.
  523. With no descendants and ref_count of 1, it has the semantics of recycle_to_reexecute. */
  524. void recycle_as_safe_continuation() {
  525. __TBB_ASSERT( prefix().state==executing, "execute not running?" );
  526. prefix().state = recycle;
  527. }
  528. //! Change this to be a child of new_parent.
  529. void recycle_as_child_of( task& new_parent ) {
  530. internal::task_prefix& p = prefix();
  531. __TBB_ASSERT( prefix().state==executing||prefix().state==allocated, "execute not running, or already recycled" );
  532. __TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled as a child" );
  533. __TBB_ASSERT( p.parent==NULL, "parent must be null" );
  534. __TBB_ASSERT( new_parent.prefix().state<=recycle, "corrupt parent's state" );
  535. __TBB_ASSERT( new_parent.prefix().state!=freed, "parent already freed" );
  536. p.state = allocated;
  537. p.parent = &new_parent;
  538. #if __TBB_TASK_GROUP_CONTEXT
  539. p.context = new_parent.prefix().context;
  540. #endif /* __TBB_TASK_GROUP_CONTEXT */
  541. }
  542. //! Schedule this for reexecution after current execute() returns.
  543. /** Made obsolete by recycle_as_safe_continuation; may become deprecated. */
  544. void recycle_to_reexecute() {
  545. __TBB_ASSERT( prefix().state==executing, "execute not running, or already recycled" );
  546. __TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled for reexecution" );
  547. prefix().state = reexecute;
  548. }
  549. #if __TBB_RECYCLE_TO_ENQUEUE
  550. //! Schedule this to enqueue after descendant tasks complete.
  551. /** Save enqueue/spawn difference, it has the semantics of recycle_as_safe_continuation. */
  552. void recycle_to_enqueue() {
  553. __TBB_ASSERT( prefix().state==executing, "execute not running, or already recycled" );
  554. prefix().state = to_enqueue;
  555. }
  556. #endif /* __TBB_RECYCLE_TO_ENQUEUE */
  557. //------------------------------------------------------------------------
  558. // Spawning and blocking
  559. //------------------------------------------------------------------------
  560. //! Set reference count
  561. void set_ref_count( int count ) {
  562. #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
  563. internal_set_ref_count(count);
  564. #else
  565. prefix().ref_count = count;
  566. #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
  567. }
  568. //! Atomically increment reference count.
  569. /** Has acquire semantics */
  570. void increment_ref_count() {
  571. __TBB_FetchAndIncrementWacquire( &prefix().ref_count );
  572. }
  573. //! Atomically adds to reference count and returns its new value.
  574. /** Has release-acquire semantics */
  575. int add_ref_count( int count ) {
  576. internal::call_itt_notify( internal::releasing, &prefix().ref_count );
  577. internal::reference_count k = count+__TBB_FetchAndAddW( &prefix().ref_count, count );
  578. __TBB_ASSERT( k>=0, "task's reference count underflowed" );
  579. if( k==0 )
  580. internal::call_itt_notify( internal::acquired, &prefix().ref_count );
  581. return int(k);
  582. }
  583. //! Atomically decrement reference count and returns its new value.
  584. /** Has release semantics. */
  585. int decrement_ref_count() {
  586. #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
  587. return int(internal_decrement_ref_count());
  588. #else
  589. return int(__TBB_FetchAndDecrementWrelease( &prefix().ref_count ))-1;
  590. #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
  591. }
  592. //! Define recommended static forms via import from base class.
  593. using task_base::spawn;
  594. //! Similar to spawn followed by wait_for_all, but more efficient.
  595. void spawn_and_wait_for_all( task& child ) {
  596. prefix().owner->wait_for_all( *this, &child );
  597. }
  598. //! Similar to spawn followed by wait_for_all, but more efficient.
  599. void __TBB_EXPORTED_METHOD spawn_and_wait_for_all( task_list& list );
  600. //! Spawn task allocated by allocate_root, wait for it to complete, and deallocate it.
  601. static void spawn_root_and_wait( task& root ) {
  602. root.prefix().owner->spawn_root_and_wait( root, root.prefix().next );
  603. }
  604. //! Spawn root tasks on list and wait for all of them to finish.
  605. /** If there are more tasks than worker threads, the tasks are spawned in
  606. order of front to back. */
  607. static void spawn_root_and_wait( task_list& root_list );
  608. //! Wait for reference count to become one, and set reference count to zero.
  609. /** Works on tasks while waiting. */
  610. void wait_for_all() {
  611. prefix().owner->wait_for_all( *this, NULL );
  612. }
  613. //! Enqueue task for starvation-resistant execution.
  614. #if __TBB_TASK_PRIORITY
  615. /** The task will be enqueued on the normal priority level disregarding the
  616. priority of its task group.
  617. The rationale of such semantics is that priority of an enqueued task is
  618. statically fixed at the moment of its enqueuing, while task group priority
  619. is dynamic. Thus automatic priority inheritance would be generally a subject
  620. to the race, which may result in unexpected behavior.
  621. Use enqueue() overload with explicit priority value and task::group_priority()
  622. method to implement such priority inheritance when it is really necessary. **/
  623. #endif /* __TBB_TASK_PRIORITY */
  624. static void enqueue( task& t ) {
  625. t.prefix().owner->enqueue( t, NULL );
  626. }
  627. #if __TBB_TASK_PRIORITY
  628. //! Enqueue task for starvation-resistant execution on the specified priority level.
  629. static void enqueue( task& t, priority_t p ) {
  630. __TBB_ASSERT( p == priority_low || p == priority_normal || p == priority_high, "Invalid priority level value" );
  631. t.prefix().owner->enqueue( t, (void*)p );
  632. }
  633. #endif /* __TBB_TASK_PRIORITY */
  634. //! The innermost task being executed or destroyed by the current thread at the moment.
  635. static task& __TBB_EXPORTED_FUNC self();
  636. //! task on whose behalf this task is working, or NULL if this is a root.
  637. task* parent() const {return prefix().parent;}
  638. //! sets parent task pointer to specified value
  639. void set_parent(task* p) {
  640. #if __TBB_TASK_GROUP_CONTEXT
  641. __TBB_ASSERT(!p || prefix().context == p->prefix().context, "The tasks must be in the same context");
  642. #endif
  643. prefix().parent = p;
  644. }
  645. #if __TBB_TASK_GROUP_CONTEXT
  646. //! This method is deprecated and will be removed in the future.
  647. /** Use method group() instead. **/
  648. task_group_context* context() {return prefix().context;}
  649. //! Pointer to the task group descriptor.
  650. task_group_context* group () { return prefix().context; }
  651. #endif /* __TBB_TASK_GROUP_CONTEXT */
  652. //! True if task was stolen from the task pool of another thread.
  653. bool is_stolen_task() const {
  654. return (prefix().extra_state & 0x80)!=0;
  655. }
  656. //------------------------------------------------------------------------
  657. // Debugging
  658. //------------------------------------------------------------------------
  659. //! Current execution state
  660. state_type state() const {return state_type(prefix().state);}
  661. //! The internal reference count.
  662. int ref_count() const {
  663. #if TBB_USE_ASSERT
  664. internal::reference_count ref_count_ = prefix().ref_count;
  665. __TBB_ASSERT( ref_count_==int(ref_count_), "integer overflow error");
  666. #endif
  667. return int(prefix().ref_count);
  668. }
  669. //! Obsolete, and only retained for the sake of backward compatibility. Always returns true.
  670. bool __TBB_EXPORTED_METHOD is_owned_by_current_thread() const;
  671. //------------------------------------------------------------------------
  672. // Affinity
  673. //------------------------------------------------------------------------
  674. //! An id as used for specifying affinity.
  675. /** Guaranteed to be integral type. Value of 0 means no affinity. */
  676. typedef internal::affinity_id affinity_id;
  677. //! Set affinity for this task.
  678. void set_affinity( affinity_id id ) {prefix().affinity = id;}
  679. //! Current affinity of this task
  680. affinity_id affinity() const {return prefix().affinity;}
  681. //! Invoked by scheduler to notify task that it ran on unexpected thread.
  682. /** Invoked before method execute() runs, if task is stolen, or task has
  683. affinity but will be executed on another thread.
  684. The default action does nothing. */
  685. virtual void __TBB_EXPORTED_METHOD note_affinity( affinity_id id );
  686. #if __TBB_TASK_GROUP_CONTEXT
  687. //! Moves this task from its current group into another one.
  688. /** Argument ctx specifies the new group.
  689. The primary purpose of this method is to associate unique task group context
  690. with a task allocated for subsequent enqueuing. In contrast to spawned tasks
  691. enqueued ones normally outlive the scope where they were created. This makes
  692. traditional usage model where task group context are allocated locally on
  693. the stack inapplicable. Dynamic allocation of context objects is performance
  694. inefficient. Method change_group() allows to make task group context object
  695. a member of the task class, and then associate it with its containing task
  696. object in the latter's constructor. **/
  697. void __TBB_EXPORTED_METHOD change_group ( task_group_context& ctx );
  698. //! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
  699. /** \return false if cancellation has already been requested, true otherwise. **/
  700. bool cancel_group_execution () { return prefix().context->cancel_group_execution(); }
  701. //! Returns true if the context has received cancellation request.
  702. bool is_cancelled () const { return prefix().context->is_group_execution_cancelled(); }
  703. #else
  704. bool is_cancelled () const { return false; }
  705. #endif /* __TBB_TASK_GROUP_CONTEXT */
  706. #if __TBB_TASK_PRIORITY
  707. //! Changes priority of the task group this task belongs to.
  708. void set_group_priority ( priority_t p ) { prefix().context->set_priority(p); }
  709. //! Retrieves current priority of the task group this task belongs to.
  710. priority_t group_priority () const { return prefix().context->priority(); }
  711. #endif /* __TBB_TASK_PRIORITY */
  712. private:
  713. friend class interface5::internal::task_base;
  714. friend class task_list;
  715. friend class internal::scheduler;
  716. friend class internal::allocate_root_proxy;
  717. #if __TBB_TASK_GROUP_CONTEXT
  718. friend class internal::allocate_root_with_context_proxy;
  719. #endif /* __TBB_TASK_GROUP_CONTEXT */
  720. friend class internal::allocate_continuation_proxy;
  721. friend class internal::allocate_child_proxy;
  722. friend class internal::allocate_additional_child_of_proxy;
  723. //! Get reference to corresponding task_prefix.
  724. /** Version tag prevents loader on Linux from using the wrong symbol in debug builds. **/
  725. internal::task_prefix& prefix( internal::version_tag* = NULL ) const {
  726. return reinterpret_cast<internal::task_prefix*>(const_cast<task*>(this))[-1];
  727. }
  728. }; // class task
  729. //! task that does nothing. Useful for synchronization.
  730. /** @ingroup task_scheduling */
  731. class empty_task: public task {
  732. /*override*/ task* execute() {
  733. return NULL;
  734. }
  735. };
  736. //! @cond INTERNAL
  737. namespace internal {
  738. template<typename F>
  739. class function_task : public task {
  740. F my_func;
  741. /*override*/ task* execute() {
  742. my_func();
  743. return NULL;
  744. }
  745. public:
  746. function_task( const F& f ) : my_func(f) {}
  747. };
  748. } // namespace internal
  749. //! @endcond
  750. //! A list of children.
  751. /** Used for method task::spawn_children
  752. @ingroup task_scheduling */
  753. class task_list: internal::no_copy {
  754. private:
  755. task* first;
  756. task** next_ptr;
  757. friend class task;
  758. friend class interface5::internal::task_base;
  759. public:
  760. //! Construct empty list
  761. task_list() : first(NULL), next_ptr(&first) {}
  762. //! Destroys the list, but does not destroy the task objects.
  763. ~task_list() {}
  764. //! True if list if empty; false otherwise.
  765. bool empty() const {return !first;}
  766. //! Push task onto back of list.
  767. void push_back( task& task ) {
  768. task.prefix().next = NULL;
  769. *next_ptr = &task;
  770. next_ptr = &task.prefix().next;
  771. }
  772. #if __TBB_TODO
  773. // TODO: add this method and implement&document the local execution ordering. See more in generic_scheduler::local_spawn
  774. //! Push task onto front of list (FIFO local execution, like individual spawning in the same order).
  775. void push_front( task& task ) {
  776. if( empty() ) {
  777. push_back(task);
  778. } else {
  779. task.prefix().next = first;
  780. first = &task;
  781. }
  782. }
  783. #endif
  784. //! Pop the front task from the list.
  785. task& pop_front() {
  786. __TBB_ASSERT( !empty(), "attempt to pop item from empty task_list" );
  787. task* result = first;
  788. first = result->prefix().next;
  789. if( !first ) next_ptr = &first;
  790. return *result;
  791. }
  792. //! Clear the list
  793. void clear() {
  794. first=NULL;
  795. next_ptr=&first;
  796. }
  797. };
  798. inline void interface5::internal::task_base::spawn( task& t ) {
  799. t.prefix().owner->spawn( t, t.prefix().next );
  800. }
  801. inline void interface5::internal::task_base::spawn( task_list& list ) {
  802. if( task* t = list.first ) {
  803. t->prefix().owner->spawn( *t, *list.next_ptr );
  804. list.clear();
  805. }
  806. }
  807. inline void task::spawn_root_and_wait( task_list& root_list ) {
  808. if( task* t = root_list.first ) {
  809. t->prefix().owner->spawn_root_and_wait( *t, *root_list.next_ptr );
  810. root_list.clear();
  811. }
  812. }
  813. } // namespace tbb
  814. inline void *operator new( size_t bytes, const tbb::internal::allocate_root_proxy& ) {
  815. return &tbb::internal::allocate_root_proxy::allocate(bytes);
  816. }
  817. inline void operator delete( void* task, const tbb::internal::allocate_root_proxy& ) {
  818. tbb::internal::allocate_root_proxy::free( *static_cast<tbb::task*>(task) );
  819. }
  820. #if __TBB_TASK_GROUP_CONTEXT
  821. inline void *operator new( size_t bytes, const tbb::internal::allocate_root_with_context_proxy& p ) {
  822. return &p.allocate(bytes);
  823. }
  824. inline void operator delete( void* task, const tbb::internal::allocate_root_with_context_proxy& p ) {
  825. p.free( *static_cast<tbb::task*>(task) );
  826. }
  827. #endif /* __TBB_TASK_GROUP_CONTEXT */
  828. inline void *operator new( size_t bytes, const tbb::internal::allocate_continuation_proxy& p ) {
  829. return &p.allocate(bytes);
  830. }
  831. inline void operator delete( void* task, const tbb::internal::allocate_continuation_proxy& p ) {
  832. p.free( *static_cast<tbb::task*>(task) );
  833. }
  834. inline void *operator new( size_t bytes, const tbb::internal::allocate_child_proxy& p ) {
  835. return &p.allocate(bytes);
  836. }
  837. inline void operator delete( void* task, const tbb::internal::allocate_child_proxy& p ) {
  838. p.free( *static_cast<tbb::task*>(task) );
  839. }
  840. inline void *operator new( size_t bytes, const tbb::internal::allocate_additional_child_of_proxy& p ) {
  841. return &p.allocate(bytes);
  842. }
  843. inline void operator delete( void* task, const tbb::internal::allocate_additional_child_of_proxy& p ) {
  844. p.free( *static_cast<tbb::task*>(task) );
  845. }
  846. #endif /* __TBB_task_H */