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.

992 lines
39 KiB

  1. /*
  2. Copyright 2005-2014 Intel Corporation. All Rights Reserved.
  3. This file is part of Threading Building Blocks.
  4. Threading Building Blocks is free software; you can redistribute it
  5. and/or modify it under the terms of the GNU General Public License
  6. version 2 as published by the Free Software Foundation.
  7. Threading Building Blocks is distributed in the hope that it will be
  8. useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  9. of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with Threading Building Blocks; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. As a special exception, you may use this file as part of a free software
  15. library without restriction. Specifically, if other files instantiate
  16. templates or use macros or inline functions from this file, or you compile
  17. this file and link it with other files to produce an executable, this
  18. file does not by itself cause the resulting executable to be covered by
  19. the GNU General Public License. This exception does not however
  20. invalidate any other reasons why the executable file might be covered by
  21. the GNU General Public License.
  22. */
  23. #ifndef __TBB_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 { //< @cond 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. } //< namespace internal @endcond
  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. // TODO: describe asynchronous use, and whether any memory semantics are needed
  286. __TBB_atomic kind_type my_kind;
  287. uintptr_t _my_kind_aligner;
  288. };
  289. //! Pointer to the context of the parent cancellation group. NULL for isolated contexts.
  290. task_group_context *my_parent;
  291. //! Used to form the thread specific list of contexts without additional memory allocation.
  292. /** A context is included into the list of the current thread when its binding to
  293. its parent happens. Any context can be present in the list of one thread only. **/
  294. internal::context_list_node_t my_node;
  295. //! Used to set and maintain stack stitching point for Intel Performance Tools.
  296. __itt_caller itt_caller;
  297. //! Leading padding protecting accesses to frequently used members from false sharing.
  298. /** Read accesses to the field my_cancellation_requested are on the hot path inside
  299. the scheduler. This padding ensures that this field never shares the same cache
  300. line with a local variable that is frequently written to. **/
  301. char _leading_padding[internal::NFS_MaxLineSize
  302. - 2 * sizeof(uintptr_t)- sizeof(void*) - sizeof(internal::context_list_node_t)
  303. - sizeof(__itt_caller)];
  304. //! Specifies whether cancellation was requested for this task group.
  305. uintptr_t my_cancellation_requested;
  306. //! Version for run-time checks and behavioral traits of the context.
  307. /** Version occupies low 16 bits, and traits (zero or more ORed enumerators
  308. from the traits_type enumerations) take the next 16 bits.
  309. Original (zeroth) version of the context did not support any traits. **/
  310. uintptr_t my_version_and_traits;
  311. //! Pointer to the container storing exception being propagated across this task group.
  312. exception_container_type *my_exception;
  313. //! Scheduler instance that registered this context in its thread specific list.
  314. internal::generic_scheduler *my_owner;
  315. //! Internal state (combination of state flags, currently only may_have_children).
  316. uintptr_t my_state;
  317. #if __TBB_TASK_PRIORITY
  318. //! Priority level of the task group (in normalized representation)
  319. intptr_t my_priority;
  320. #endif /* __TBB_TASK_PRIORITY */
  321. //! Trailing padding protecting accesses to frequently used members from false sharing
  322. /** \sa _leading_padding **/
  323. char _trailing_padding[internal::NFS_MaxLineSize - 2 * sizeof(uintptr_t) - 2 * sizeof(void*)
  324. #if __TBB_TASK_PRIORITY
  325. - sizeof(intptr_t)
  326. #endif /* __TBB_TASK_PRIORITY */
  327. ];
  328. public:
  329. //! Default & binding constructor.
  330. /** By default a bound context is created. That is this context will be bound
  331. (as child) to the context of the task calling task::allocate_root(this_context)
  332. method. Cancellation requests passed to the parent context are propagated
  333. to all the contexts bound to it. Similarly priority change is propagated
  334. from the parent context to its children.
  335. If task_group_context::isolated is used as the argument, then the tasks associated
  336. with this context will never be affected by events in any other context.
  337. Creating isolated contexts involve much less overhead, but they have limited
  338. utility. Normally when an exception occurs in an algorithm that has nested
  339. ones running, it is desirably to have all the nested algorithms cancelled
  340. as well. Such a behavior requires nested algorithms to use bound contexts.
  341. There is one good place where using isolated algorithms is beneficial. It is
  342. a master thread. That is if a particular algorithm is invoked directly from
  343. the master thread (not from a TBB task), supplying it with explicitly
  344. created isolated context will result in a faster algorithm startup.
  345. VERSIONING NOTE:
  346. Implementation(s) of task_group_context constructor(s) cannot be made
  347. entirely out-of-line because the run-time version must be set by the user
  348. code. This will become critically important for binary compatibility, if
  349. we ever have to change the size of the context object.
  350. Boosting the runtime version will also be necessary if new data fields are
  351. introduced in the currently unused padding areas and these fields are updated
  352. by inline methods. **/
  353. task_group_context ( kind_type relation_with_parent = bound,
  354. uintptr_t traits = default_traits )
  355. : my_kind(relation_with_parent)
  356. , my_version_and_traits(1 | traits)
  357. {
  358. init();
  359. }
  360. // Do not introduce standalone unbind method since it will break state propagation assumptions
  361. __TBB_EXPORTED_METHOD ~task_group_context ();
  362. //! Forcefully reinitializes the context after the task tree it was associated with is completed.
  363. /** Because the method assumes that all the tasks that used to be associated with
  364. this context have already finished, calling it while the context is still
  365. in use somewhere in the task hierarchy leads to undefined behavior.
  366. IMPORTANT: This method is not thread safe!
  367. The method does not change the context's parent if it is set. **/
  368. void __TBB_EXPORTED_METHOD reset ();
  369. //! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
  370. /** \return false if cancellation has already been requested, true otherwise.
  371. Note that canceling never fails. When false is returned, it just means that
  372. another thread (or this one) has already sent cancellation request to this
  373. context or to one of its ancestors (if this context is bound). It is guaranteed
  374. that when this method is concurrently called on the same not yet cancelled
  375. context, true will be returned by one and only one invocation. **/
  376. bool __TBB_EXPORTED_METHOD cancel_group_execution ();
  377. //! Returns true if the context received cancellation request.
  378. bool __TBB_EXPORTED_METHOD is_group_execution_cancelled () const;
  379. //! Records the pending exception, and cancels the task group.
  380. /** May be called only from inside a catch-block. If the context is already
  381. cancelled, does nothing.
  382. The method brings the task group associated with this context exactly into
  383. the state it would be in, if one of its tasks threw the currently pending
  384. exception during its execution. In other words, it emulates the actions
  385. of the scheduler's dispatch loop exception handler. **/
  386. void __TBB_EXPORTED_METHOD register_pending_exception ();
  387. #if __TBB_TASK_PRIORITY
  388. //! Changes priority of the task group
  389. void set_priority ( priority_t );
  390. //! Retrieves current priority of the current task group
  391. priority_t priority () const;
  392. #endif /* __TBB_TASK_PRIORITY */
  393. protected:
  394. //! Out-of-line part of the constructor.
  395. /** Singled out to ensure backward binary compatibility of the future versions. **/
  396. void __TBB_EXPORTED_METHOD init ();
  397. private:
  398. friend class task;
  399. friend class internal::allocate_root_with_context_proxy;
  400. static const kind_type binding_required = bound;
  401. static const kind_type binding_completed = kind_type(bound+1);
  402. static const kind_type detached = kind_type(binding_completed+1);
  403. static const kind_type dying = kind_type(detached+1);
  404. //! Propagates any state change detected to *this, and as an optimisation possibly also upward along the heritage line.
  405. template <typename T>
  406. void propagate_task_group_state ( T task_group_context::*mptr_state, task_group_context& src, 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. #if __TBB_RECYCLE_TO_ENQUEUE
  445. //! task to be scheduled for starvation-resistant execution
  446. ,to_enqueue
  447. #endif
  448. };
  449. //------------------------------------------------------------------------
  450. // Allocating tasks
  451. //------------------------------------------------------------------------
  452. //! Returns proxy for overloaded new that allocates a root task.
  453. static internal::allocate_root_proxy allocate_root() {
  454. return internal::allocate_root_proxy();
  455. }
  456. #if __TBB_TASK_GROUP_CONTEXT
  457. //! Returns proxy for overloaded new that allocates a root task associated with user supplied context.
  458. static internal::allocate_root_with_context_proxy allocate_root( task_group_context& ctx ) {
  459. return internal::allocate_root_with_context_proxy(ctx);
  460. }
  461. #endif /* __TBB_TASK_GROUP_CONTEXT */
  462. //! Returns proxy for overloaded new that allocates a continuation task of *this.
  463. /** The continuation's parent becomes the parent of *this. */
  464. internal::allocate_continuation_proxy& allocate_continuation() {
  465. return *reinterpret_cast<internal::allocate_continuation_proxy*>(this);
  466. }
  467. //! Returns proxy for overloaded new that allocates a child task of *this.
  468. internal::allocate_child_proxy& allocate_child() {
  469. return *reinterpret_cast<internal::allocate_child_proxy*>(this);
  470. }
  471. //! Define recommended static form via import from base class.
  472. using task_base::allocate_additional_child_of;
  473. #if __TBB_DEPRECATED_TASK_INTERFACE
  474. //! Destroy a task.
  475. /** Usually, calling this method is unnecessary, because a task is
  476. implicitly deleted after its execute() method runs. However,
  477. sometimes a task needs to be explicitly deallocated, such as
  478. when a root task is used as the parent in spawn_and_wait_for_all. */
  479. void __TBB_EXPORTED_METHOD destroy( task& t );
  480. #else /* !__TBB_DEPRECATED_TASK_INTERFACE */
  481. //! Define recommended static form via import from base class.
  482. using task_base::destroy;
  483. #endif /* !__TBB_DEPRECATED_TASK_INTERFACE */
  484. //------------------------------------------------------------------------
  485. // Recycling of tasks
  486. //------------------------------------------------------------------------
  487. //! Change this to be a continuation of its former self.
  488. /** The caller must guarantee that the task's refcount does not become zero until
  489. after the method execute() returns. Typically, this is done by having
  490. method execute() return a pointer to a child of the task. If the guarantee
  491. cannot be made, use method recycle_as_safe_continuation instead.
  492. Because of the hazard, this method may be deprecated in the future. */
  493. void recycle_as_continuation() {
  494. __TBB_ASSERT( prefix().state==executing, "execute not running?" );
  495. prefix().state = allocated;
  496. }
  497. //! Recommended to use, safe variant of recycle_as_continuation
  498. /** For safety, it requires additional increment of ref_count.
  499. With no descendants and ref_count of 1, it has the semantics of recycle_to_reexecute. */
  500. void recycle_as_safe_continuation() {
  501. __TBB_ASSERT( prefix().state==executing, "execute not running?" );
  502. prefix().state = recycle;
  503. }
  504. //! Change this to be a child of new_parent.
  505. void recycle_as_child_of( task& new_parent ) {
  506. internal::task_prefix& p = prefix();
  507. __TBB_ASSERT( prefix().state==executing||prefix().state==allocated, "execute not running, or already recycled" );
  508. __TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled as a child" );
  509. __TBB_ASSERT( p.parent==NULL, "parent must be null" );
  510. __TBB_ASSERT( new_parent.prefix().state<=recycle, "corrupt parent's state" );
  511. __TBB_ASSERT( new_parent.prefix().state!=freed, "parent already freed" );
  512. p.state = allocated;
  513. p.parent = &new_parent;
  514. #if __TBB_TASK_GROUP_CONTEXT
  515. p.context = new_parent.prefix().context;
  516. #endif /* __TBB_TASK_GROUP_CONTEXT */
  517. }
  518. //! Schedule this for reexecution after current execute() returns.
  519. /** Made obsolete by recycle_as_safe_continuation; may become deprecated. */
  520. void recycle_to_reexecute() {
  521. __TBB_ASSERT( prefix().state==executing, "execute not running, or already recycled" );
  522. __TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled for reexecution" );
  523. prefix().state = reexecute;
  524. }
  525. #if __TBB_RECYCLE_TO_ENQUEUE
  526. //! Schedule this to enqueue after descendant tasks complete.
  527. /** Save enqueue/spawn difference, it has the semantics of recycle_as_safe_continuation. */
  528. void recycle_to_enqueue() {
  529. __TBB_ASSERT( prefix().state==executing, "execute not running, or already recycled" );
  530. prefix().state = to_enqueue;
  531. }
  532. #endif /* __TBB_RECYCLE_TO_ENQUEUE */
  533. // All depth-related methods are obsolete, and are retained for the sake
  534. // of backward source compatibility only
  535. intptr_t depth() const {return 0;}
  536. void set_depth( intptr_t ) {}
  537. void add_to_depth( int ) {}
  538. //------------------------------------------------------------------------
  539. // Spawning and blocking
  540. //------------------------------------------------------------------------
  541. //! Set reference count
  542. void set_ref_count( int count ) {
  543. #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
  544. internal_set_ref_count(count);
  545. #else
  546. prefix().ref_count = count;
  547. #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
  548. }
  549. //! Atomically increment reference count and returns its old value.
  550. /** Has acquire semantics */
  551. void increment_ref_count() {
  552. __TBB_FetchAndIncrementWacquire( &prefix().ref_count );
  553. }
  554. //! Atomically decrement reference count and returns its new value.
  555. /** Has release semantics. */
  556. int decrement_ref_count() {
  557. #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
  558. return int(internal_decrement_ref_count());
  559. #else
  560. return int(__TBB_FetchAndDecrementWrelease( &prefix().ref_count ))-1;
  561. #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
  562. }
  563. //! Define recommended static forms via import from base class.
  564. using task_base::spawn;
  565. //! Similar to spawn followed by wait_for_all, but more efficient.
  566. void spawn_and_wait_for_all( task& child ) {
  567. prefix().owner->wait_for_all( *this, &child );
  568. }
  569. //! Similar to spawn followed by wait_for_all, but more efficient.
  570. void __TBB_EXPORTED_METHOD spawn_and_wait_for_all( task_list& list );
  571. //! Spawn task allocated by allocate_root, wait for it to complete, and deallocate it.
  572. static void spawn_root_and_wait( task& root ) {
  573. root.prefix().owner->spawn_root_and_wait( root, root.prefix().next );
  574. }
  575. //! Spawn root tasks on list and wait for all of them to finish.
  576. /** If there are more tasks than worker threads, the tasks are spawned in
  577. order of front to back. */
  578. static void spawn_root_and_wait( task_list& root_list );
  579. //! Wait for reference count to become one, and set reference count to zero.
  580. /** Works on tasks while waiting. */
  581. void wait_for_all() {
  582. prefix().owner->wait_for_all( *this, NULL );
  583. }
  584. //! Enqueue task for starvation-resistant execution.
  585. #if __TBB_TASK_PRIORITY
  586. /** The task will be enqueued on the normal priority level disregarding the
  587. priority of its task group.
  588. The rationale of such semantics is that priority of an enqueued task is
  589. statically fixed at the moment of its enqueuing, while task group priority
  590. is dynamic. Thus automatic priority inheritance would be generally a subject
  591. to the race, which may result in unexpected behavior.
  592. Use enqueue() overload with explicit priority value and task::group_priority()
  593. method to implement such priority inheritance when it is really necessary. **/
  594. #endif /* __TBB_TASK_PRIORITY */
  595. static void enqueue( task& t ) {
  596. t.prefix().owner->enqueue( t, NULL );
  597. }
  598. #if __TBB_TASK_PRIORITY
  599. //! Enqueue task for starvation-resistant execution on the specified priority level.
  600. static void enqueue( task& t, priority_t p ) {
  601. __TBB_ASSERT( p == priority_low || p == priority_normal || p == priority_high, "Invalid priority level value" );
  602. t.prefix().owner->enqueue( t, (void*)p );
  603. }
  604. #endif /* __TBB_TASK_PRIORITY */
  605. //! The innermost task being executed or destroyed by the current thread at the moment.
  606. static task& __TBB_EXPORTED_FUNC self();
  607. //! task on whose behalf this task is working, or NULL if this is a root.
  608. task* parent() const {return prefix().parent;}
  609. //! sets parent task pointer to specified value
  610. void set_parent(task* p) {
  611. #if __TBB_TASK_GROUP_CONTEXT
  612. __TBB_ASSERT(prefix().context == p->prefix().context, "The tasks must be in the same context");
  613. #endif
  614. prefix().parent = p;
  615. }
  616. #if __TBB_TASK_GROUP_CONTEXT
  617. //! This method is deprecated and will be removed in the future.
  618. /** Use method group() instead. **/
  619. task_group_context* context() {return prefix().context;}
  620. //! Pointer to the task group descriptor.
  621. task_group_context* group () { return prefix().context; }
  622. #endif /* __TBB_TASK_GROUP_CONTEXT */
  623. //! True if task was stolen from the task pool of another thread.
  624. bool is_stolen_task() const {
  625. return (prefix().extra_state & 0x80)!=0;
  626. }
  627. //------------------------------------------------------------------------
  628. // Debugging
  629. //------------------------------------------------------------------------
  630. //! Current execution state
  631. state_type state() const {return state_type(prefix().state);}
  632. //! The internal reference count.
  633. int ref_count() const {
  634. #if TBB_USE_ASSERT
  635. internal::reference_count ref_count_ = prefix().ref_count;
  636. __TBB_ASSERT( ref_count_==int(ref_count_), "integer overflow error");
  637. #endif
  638. return int(prefix().ref_count);
  639. }
  640. //! Obsolete, and only retained for the sake of backward compatibility. Always returns true.
  641. bool __TBB_EXPORTED_METHOD is_owned_by_current_thread() const;
  642. //------------------------------------------------------------------------
  643. // Affinity
  644. //------------------------------------------------------------------------
  645. //! An id as used for specifying affinity.
  646. /** Guaranteed to be integral type. Value of 0 means no affinity. */
  647. typedef internal::affinity_id affinity_id;
  648. //! Set affinity for this task.
  649. void set_affinity( affinity_id id ) {prefix().affinity = id;}
  650. //! Current affinity of this task
  651. affinity_id affinity() const {return prefix().affinity;}
  652. //! Invoked by scheduler to notify task that it ran on unexpected thread.
  653. /** Invoked before method execute() runs, if task is stolen, or task has
  654. affinity but will be executed on another thread.
  655. The default action does nothing. */
  656. virtual void __TBB_EXPORTED_METHOD note_affinity( affinity_id id );
  657. #if __TBB_TASK_GROUP_CONTEXT
  658. //! Moves this task from its current group into another one.
  659. /** Argument ctx specifies the new group.
  660. The primary purpose of this method is to associate unique task group context
  661. with a task allocated for subsequent enqueuing. In contrast to spawned tasks
  662. enqueued ones normally outlive the scope where they were created. This makes
  663. traditional usage model where task group context are allocated locally on
  664. the stack inapplicable. Dynamic allocation of context objects is performance
  665. inefficient. Method change_group() allows to make task group context object
  666. a member of the task class, and then associate it with its containing task
  667. object in the latter's constructor. **/
  668. void __TBB_EXPORTED_METHOD change_group ( task_group_context& ctx );
  669. //! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
  670. /** \return false if cancellation has already been requested, true otherwise. **/
  671. bool cancel_group_execution () { return prefix().context->cancel_group_execution(); }
  672. //! Returns true if the context has received cancellation request.
  673. bool is_cancelled () const { return prefix().context->is_group_execution_cancelled(); }
  674. #else
  675. bool is_cancelled () const { return false; }
  676. #endif /* __TBB_TASK_GROUP_CONTEXT */
  677. #if __TBB_TASK_PRIORITY
  678. //! Changes priority of the task group this task belongs to.
  679. void set_group_priority ( priority_t p ) { prefix().context->set_priority(p); }
  680. //! Retrieves current priority of the task group this task belongs to.
  681. priority_t group_priority () const { return prefix().context->priority(); }
  682. #endif /* __TBB_TASK_PRIORITY */
  683. private:
  684. friend class interface5::internal::task_base;
  685. friend class task_list;
  686. friend class internal::scheduler;
  687. friend class internal::allocate_root_proxy;
  688. #if __TBB_TASK_GROUP_CONTEXT
  689. friend class internal::allocate_root_with_context_proxy;
  690. #endif /* __TBB_TASK_GROUP_CONTEXT */
  691. friend class internal::allocate_continuation_proxy;
  692. friend class internal::allocate_child_proxy;
  693. friend class internal::allocate_additional_child_of_proxy;
  694. //! Get reference to corresponding task_prefix.
  695. /** Version tag prevents loader on Linux from using the wrong symbol in debug builds. **/
  696. internal::task_prefix& prefix( internal::version_tag* = NULL ) const {
  697. return reinterpret_cast<internal::task_prefix*>(const_cast<task*>(this))[-1];
  698. }
  699. }; // class task
  700. //! task that does nothing. Useful for synchronization.
  701. /** @ingroup task_scheduling */
  702. class empty_task: public task {
  703. /*override*/ task* execute() {
  704. return NULL;
  705. }
  706. };
  707. //! @cond INTERNAL
  708. namespace internal {
  709. template<typename F>
  710. class function_task : public task {
  711. F my_func;
  712. /*override*/ task* execute() {
  713. my_func();
  714. return NULL;
  715. }
  716. public:
  717. function_task( const F& f ) : my_func(f) {}
  718. };
  719. } // namespace internal
  720. //! @endcond
  721. //! A list of children.
  722. /** Used for method task::spawn_children
  723. @ingroup task_scheduling */
  724. class task_list: internal::no_copy {
  725. private:
  726. task* first;
  727. task** next_ptr;
  728. friend class task;
  729. friend class interface5::internal::task_base;
  730. public:
  731. //! Construct empty list
  732. task_list() : first(NULL), next_ptr(&first) {}
  733. //! Destroys the list, but does not destroy the task objects.
  734. ~task_list() {}
  735. //! True if list if empty; false otherwise.
  736. bool empty() const {return !first;}
  737. //! Push task onto back of list.
  738. void push_back( task& task ) {
  739. task.prefix().next = NULL;
  740. *next_ptr = &task;
  741. next_ptr = &task.prefix().next;
  742. }
  743. //! Pop the front task from the list.
  744. task& pop_front() {
  745. __TBB_ASSERT( !empty(), "attempt to pop item from empty task_list" );
  746. task* result = first;
  747. first = result->prefix().next;
  748. if( !first ) next_ptr = &first;
  749. return *result;
  750. }
  751. //! Clear the list
  752. void clear() {
  753. first=NULL;
  754. next_ptr=&first;
  755. }
  756. };
  757. inline void interface5::internal::task_base::spawn( task& t ) {
  758. t.prefix().owner->spawn( t, t.prefix().next );
  759. }
  760. inline void interface5::internal::task_base::spawn( task_list& list ) {
  761. if( task* t = list.first ) {
  762. t->prefix().owner->spawn( *t, *list.next_ptr );
  763. list.clear();
  764. }
  765. }
  766. inline void task::spawn_root_and_wait( task_list& root_list ) {
  767. if( task* t = root_list.first ) {
  768. t->prefix().owner->spawn_root_and_wait( *t, *root_list.next_ptr );
  769. root_list.clear();
  770. }
  771. }
  772. } // namespace tbb
  773. inline void *operator new( size_t bytes, const tbb::internal::allocate_root_proxy& ) {
  774. return &tbb::internal::allocate_root_proxy::allocate(bytes);
  775. }
  776. inline void operator delete( void* task, const tbb::internal::allocate_root_proxy& ) {
  777. tbb::internal::allocate_root_proxy::free( *static_cast<tbb::task*>(task) );
  778. }
  779. #if __TBB_TASK_GROUP_CONTEXT
  780. inline void *operator new( size_t bytes, const tbb::internal::allocate_root_with_context_proxy& p ) {
  781. return &p.allocate(bytes);
  782. }
  783. inline void operator delete( void* task, const tbb::internal::allocate_root_with_context_proxy& p ) {
  784. p.free( *static_cast<tbb::task*>(task) );
  785. }
  786. #endif /* __TBB_TASK_GROUP_CONTEXT */
  787. inline void *operator new( size_t bytes, const tbb::internal::allocate_continuation_proxy& p ) {
  788. return &p.allocate(bytes);
  789. }
  790. inline void operator delete( void* task, const tbb::internal::allocate_continuation_proxy& p ) {
  791. p.free( *static_cast<tbb::task*>(task) );
  792. }
  793. inline void *operator new( size_t bytes, const tbb::internal::allocate_child_proxy& p ) {
  794. return &p.allocate(bytes);
  795. }
  796. inline void operator delete( void* task, const tbb::internal::allocate_child_proxy& p ) {
  797. p.free( *static_cast<tbb::task*>(task) );
  798. }
  799. inline void *operator new( size_t bytes, const tbb::internal::allocate_additional_child_of_proxy& p ) {
  800. return &p.allocate(bytes);
  801. }
  802. inline void operator delete( void* task, const tbb::internal::allocate_additional_child_of_proxy& p ) {
  803. p.free( *static_cast<tbb::task*>(task) );
  804. }
  805. #endif /* __TBB_task_H */