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.

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