2 Copyright 2005-2011 Intel Corporation. All Rights Reserved.
4 This file is part of Threading Building Blocks.
6 Threading Building Blocks is free software; you can redistribute it
7 and/or modify it under the terms of the GNU General Public License
8 version 2 as published by the Free Software Foundation.
10 Threading Building Blocks is distributed in the hope that it will be
11 useful, but WITHOUT ANY WARRANTY; without even the implied warranty
12 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with Threading Building Blocks; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 As a special exception, you may use this file as part of a free software
20 library without restriction. Specifically, if other files instantiate
21 templates or use macros or inline functions from this file, or you compile
22 this file and link it with other files to produce an executable, this
23 file does not by itself cause the resulting executable to be covered by
24 the GNU General Public License. This exception does not however
25 invalidate any other reasons why the executable file might be covered by
26 the GNU General Public License.
32 #include "tbb_stddef.h"
33 #include "tbb_machine.h"
36 typedef struct ___itt_caller *__itt_caller;
43 #if __TBB_TASK_GROUP_CONTEXT
44 class task_group_context;
45 #endif /* __TBB_TASK_GROUP_CONTEXT */
47 // MSVC does not allow taking the address of a member that was defined
48 // privately in task_base and made public in class task via a using declaration.
49 #if _MSC_VER || (__GNUC__==3 && __GNUC_MINOR__<3)
50 #define __TBB_TASK_BASE_ACCESS public
52 #define __TBB_TASK_BASE_ACCESS private
57 class allocate_additional_child_of_proxy: no_assign {
58 //! No longer used, but retained for binary layout compatibility. Always NULL.
62 explicit allocate_additional_child_of_proxy( task& parent_ ) : self(NULL), parent(parent_) {}
63 task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
64 void __TBB_EXPORTED_METHOD free( task& ) const;
69 namespace interface5 {
71 //! Base class for methods that became static in TBB 3.0.
72 /** TBB's evolution caused the "this" argument for several methods to become obsolete.
73 However, for backwards binary compatibility, the new methods need distinct names,
74 otherwise the One Definition Rule would be broken. Hence the new methods are
75 defined in this private base class, and then exposed in class task via
76 using declarations. */
77 class task_base: tbb::internal::no_copy {
78 __TBB_TASK_BASE_ACCESS:
79 friend class tbb::task;
81 //! Schedule task for execution when a worker becomes available.
82 static void spawn( task& t );
84 //! Spawn multiple tasks and clear list.
85 static void spawn( task_list& list );
87 //! Like allocate_child, except that task's parent becomes "t", not this.
88 /** Typically used in conjunction with schedule_to_reexecute to implement while loops.
89 Atomically increments the reference count of t.parent() */
90 static tbb::internal::allocate_additional_child_of_proxy allocate_additional_child_of( task& t ) {
91 return tbb::internal::allocate_additional_child_of_proxy(t);
95 /** Usually, calling this method is unnecessary, because a task is
96 implicitly deleted after its execute() method runs. However,
97 sometimes a task needs to be explicitly deallocated, such as
98 when a root task is used as the parent in spawn_and_wait_for_all. */
99 static void __TBB_EXPORTED_FUNC destroy( task& victim );
107 class scheduler: no_copy {
109 //! For internal use only
110 virtual void spawn( task& first, task*& next ) = 0;
112 //! For internal use only
113 virtual void wait_for_all( task& parent, task* child ) = 0;
115 //! For internal use only
116 virtual void spawn_root_and_wait( task& first, task*& next ) = 0;
118 //! Pure virtual destructor;
119 // Have to have it just to shut up overzealous compilation warnings
120 virtual ~scheduler() = 0;
122 //! For internal use only
123 virtual void enqueue( task& t, void* reserved ) = 0;
126 //! A reference count
127 /** Should always be non-negative. A signed type is used so that underflow can be detected. */
128 typedef intptr_t reference_count;
130 //! An id as used for specifying affinity.
131 typedef unsigned short affinity_id;
133 #if __TBB_TASK_GROUP_CONTEXT
134 class generic_scheduler;
136 struct context_list_node_t {
137 context_list_node_t *my_prev,
141 class allocate_root_with_context_proxy: no_assign {
142 task_group_context& my_context;
144 allocate_root_with_context_proxy ( task_group_context& ctx ) : my_context(ctx) {}
145 task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
146 void __TBB_EXPORTED_METHOD free( task& ) const;
148 #endif /* __TBB_TASK_GROUP_CONTEXT */
150 class allocate_root_proxy: no_assign {
152 static task& __TBB_EXPORTED_FUNC allocate( size_t size );
153 static void __TBB_EXPORTED_FUNC free( task& );
156 class allocate_continuation_proxy: no_assign {
158 task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
159 void __TBB_EXPORTED_METHOD free( task& ) const;
162 class allocate_child_proxy: no_assign {
164 task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
165 void __TBB_EXPORTED_METHOD free( task& ) const;
168 //! Memory prefix to a task object.
169 /** This class is internal to the library.
170 Do not reference it directly, except within the library itself.
171 Fields are ordered in way that preserves backwards compatibility and yields
172 good packing on typical 32-bit and 64-bit platforms.
173 @ingroup task_scheduling */
176 friend class tbb::task;
177 friend class tbb::interface5::internal::task_base;
178 friend class tbb::task_list;
179 friend class internal::scheduler;
180 friend class internal::allocate_root_proxy;
181 friend class internal::allocate_child_proxy;
182 friend class internal::allocate_continuation_proxy;
183 friend class internal::allocate_additional_child_of_proxy;
185 #if __TBB_TASK_GROUP_CONTEXT
186 //! Shared context that is used to communicate asynchronous state changes
187 /** Currently it is used to broadcast cancellation requests generated both
188 by users and as the result of unhandled exceptions in the task::execute()
190 task_group_context *context;
191 #endif /* __TBB_TASK_GROUP_CONTEXT */
193 //! The scheduler that allocated the task, or NULL if the task is big.
194 /** Small tasks are pooled by the scheduler that allocated the task.
195 If a scheduler needs to free a small task allocated by another scheduler,
196 it returns the task to that other scheduler. This policy avoids
197 memory space blowup issues for memory allocators that allocate from
198 thread-specific pools. */
201 #if TBB_PREVIEW_TASK_PRIORITY
203 #endif /* TBB_PREVIEW_TASK_PRIORITY */
204 //! Obsolete. The scheduler that owns the task.
205 /** Retained only for the sake of backward binary compatibility.
206 Still used by inline methods in the task.h header. **/
209 #if TBB_PREVIEW_TASK_PRIORITY
210 //! Pointer to the next offloaded lower priority task.
211 /** Used to maintain a list of offloaded tasks inside the scheduler. **/
212 task* next_offloaded;
214 #endif /* TBB_PREVIEW_TASK_PRIORITY */
216 //! The task whose reference count includes me.
217 /** In the "blocking style" of programming, this field points to the parent task.
218 In the "continuation-passing style" of programming, this field points to the
219 continuation of the parent. */
222 //! Reference count used for synchronization.
223 /** In the "continuation-passing style" of programming, this field is
224 the difference of the number of allocated children minus the
225 number of children that have completed.
226 In the "blocking style" of programming, this field is one more than the difference. */
227 reference_count ref_count;
229 //! Obsolete. Used to be scheduling depth before TBB 2.2
230 /** Retained only for the sake of backward binary compatibility.
231 Not used by TBB anymore. **/
234 //! A task::state_type, stored as a byte for compactness.
235 /** This state is exposed to users via method task::state(). */
238 //! Miscellaneous state that is not directly visible to users, stored as a byte for compactness.
239 /** 0x0 -> version 1.0 task
240 0x1 -> version >=2.1 task
242 0x40 -> task has live ref_count
243 0x80 -> a stolen task */
244 unsigned char extra_state;
246 affinity_id affinity;
248 //! "next" field for list of task
251 //! The task corresponding to this task_prefix.
252 tbb::task& task() {return *reinterpret_cast<tbb::task*>(this+1);}
255 } // namespace internal
258 #if __TBB_TASK_GROUP_CONTEXT
260 #if TBB_PREVIEW_TASK_PRIORITY
262 static const int priority_stride_v4 = INT_MAX / 4;
266 priority_normal = internal::priority_stride_v4 * 2,
267 priority_low = priority_normal - internal::priority_stride_v4,
268 priority_high = priority_normal + internal::priority_stride_v4
271 #endif /* TBB_PREVIEW_TASK_PRIORITY */
273 #if TBB_USE_CAPTURED_EXCEPTION
277 class tbb_exception_ptr;
279 #endif /* !TBB_USE_CAPTURED_EXCEPTION */
281 class task_scheduler_init;
283 //! Used to form groups of tasks
284 /** @ingroup task_scheduling
285 The context services explicit cancellation requests from user code, and unhandled
286 exceptions intercepted during tasks execution. Intercepting an exception results
287 in generating internal cancellation requests (which is processed in exactly the
288 same way as external ones).
290 The context is associated with one or more root tasks and defines the cancellation
291 group that includes all the descendants of the corresponding root task(s). Association
292 is established when a context object is passed as an argument to the task::allocate_root()
293 method. See task_group_context::task_group_context for more details.
295 The context can be bound to another one, and other contexts can be bound to it,
296 forming a tree-like structure: parent -> this -> children. Arrows here designate
297 cancellation propagation direction. If a task in a cancellation group is canceled
298 all the other tasks in this group and groups bound to it (as children) get canceled too.
301 When adding new members to task_group_context or changing types of existing ones,
302 update the size of both padding buffers (_leading_padding and _trailing_padding)
303 appropriately. See also VERSIONING NOTE at the constructor definition below. **/
304 class task_group_context : internal::no_copy {
306 friend class internal::generic_scheduler;
307 friend class task_scheduler_init;
309 #if TBB_USE_CAPTURED_EXCEPTION
310 typedef tbb_exception exception_container_type;
312 typedef internal::tbb_exception_ptr exception_container_type;
315 enum version_traits_word_layout {
317 version_mask = 0xFFFF,
318 traits_mask = 0xFFFFul << traits_offset
328 exact_exception = 0x0001ul << traits_offset,
329 concurrent_wait = 0x0004ul << traits_offset,
330 #if TBB_USE_CAPTURED_EXCEPTION
333 default_traits = exact_exception
334 #endif /* !TBB_USE_CAPTURED_EXCEPTION */
339 may_have_children = 1
343 //! Flavor of this context: bound or isolated.
345 uintptr_t _my_kind_aligner;
348 //! Pointer to the context of the parent cancellation group. NULL for isolated contexts.
349 task_group_context *my_parent;
351 //! Used to form the thread specific list of contexts without additional memory allocation.
352 /** A context is included into the list of the current thread when its binding to
353 its parent happens. Any context can be present in the list of one thread only. **/
354 internal::context_list_node_t my_node;
356 //! Used to set and maintain stack stitching point for Intel Performance Tools.
357 __itt_caller itt_caller;
359 //! Leading padding protecting accesses to frequently used members from false sharing.
360 /** Read accesses to the field my_cancellation_requested are on the hot path inside
361 the scheduler. This padding ensures that this field never shares the same cache
362 line with a local variable that is frequently written to. **/
363 char _leading_padding[internal::NFS_MaxLineSize
364 - 2 * sizeof(uintptr_t)- sizeof(void*) - sizeof(internal::context_list_node_t)
365 - sizeof(__itt_caller)];
367 //! Specifies whether cancellation was request for this task group.
368 uintptr_t my_cancellation_requested;
370 //! Version for run-time checks and behavioral traits of the context.
371 /** Version occupies low 16 bits, and traits (zero or more ORed enumerators
372 from the traits_type enumerations) take the next 16 bits.
373 Original (zeroth) version of the context did not support any traits. **/
374 uintptr_t my_version_and_traits;
376 //! Pointer to the container storing exception being propagated across this task group.
377 exception_container_type *my_exception;
379 //! Scheduler instance that registered this context in its thread specific list.
380 internal::generic_scheduler *my_owner;
382 //! Internal state (combination of state flags).
385 #if TBB_PREVIEW_TASK_PRIORITY
386 //! Priority level of the task group (in normalized representation)
387 intptr_t my_priority;
388 #endif /* TBB_PREVIEW_TASK_PRIORITY */
390 //! Trailing padding protecting accesses to frequently used members from false sharing
391 /** \sa _leading_padding **/
392 char _trailing_padding[internal::NFS_MaxLineSize - 2 * sizeof(uintptr_t) - 2 * sizeof(void*)
393 #if TBB_PREVIEW_TASK_PRIORITY
395 #endif /* TBB_PREVIEW_TASK_PRIORITY */
399 //! Default & binding constructor.
400 /** By default a bound context is created. That is this context will be bound
401 (as child) to the context of the task calling task::allocate_root(this_context)
402 method. Cancellation requests passed to the parent context are propagated
403 to all the contexts bound to it. Similarly priority change is propagated
404 from the parent context to its children.
406 If task_group_context::isolated is used as the argument, then the tasks associated
407 with this context will never be affected by events in any other context.
409 Creating isolated contexts involve much less overhead, but they have limited
410 utility. Normally when an exception occurs in an algorithm that has nested
411 ones running, it is desirably to have all the nested algorithms canceled
412 as well. Such a behavior requires nested algorithms to use bound contexts.
414 There is one good place where using isolated algorithms is beneficial. It is
415 a master thread. That is if a particular algorithm is invoked directly from
416 the master thread (not from a TBB task), supplying it with explicitly
417 created isolated context will result in a faster algorithm startup.
420 Implementation(s) of task_group_context constructor(s) cannot be made
421 entirely out-of-line because the run-time version must be set by the user
422 code. This will become critically important for binary compatibility, if
423 we ever have to change the size of the context object.
425 Boosting the runtime version will also be necessary if new data fields are
426 introduced in the currently unused padding areas and these fields are updated
427 by inline methods. **/
428 task_group_context ( kind_type relation_with_parent = bound,
429 uintptr_t traits = default_traits )
430 : my_kind(relation_with_parent)
431 , my_version_and_traits(1 | traits)
436 __TBB_EXPORTED_METHOD ~task_group_context ();
438 //! Forcefully reinitializes the context after the task tree it was associated with is completed.
439 /** Because the method assumes that all the tasks that used to be associated with
440 this context have already finished, calling it while the context is still
441 in use somewhere in the task hierarchy leads to undefined behavior.
443 IMPORTANT: This method is not thread safe!
445 The method does not change the context's parent if it is set. **/
446 void __TBB_EXPORTED_METHOD reset ();
448 //! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
449 /** \return false if cancellation has already been requested, true otherwise.
451 Note that canceling never fails. When false is returned, it just means that
452 another thread (or this one) has already sent cancellation request to this
453 context or to one of its ancestors (if this context is bound). It is guaranteed
454 that when this method is concurrently called on the same not yet cancelled
455 context, true will be returned by one and only one invocation. **/
456 bool __TBB_EXPORTED_METHOD cancel_group_execution ();
458 //! Returns true if the context received cancellation request.
459 bool __TBB_EXPORTED_METHOD is_group_execution_cancelled () const;
461 //! Records the pending exception, and cancels the task group.
462 /** May be called only from inside a catch-block. If the context is already
463 canceled, does nothing.
464 The method brings the task group associated with this context exactly into
465 the state it would be in, if one of its tasks threw the currently pending
466 exception during its execution. In other words, it emulates the actions
467 of the scheduler's dispatch loop exception handler. **/
468 void __TBB_EXPORTED_METHOD register_pending_exception ();
470 #if TBB_PREVIEW_TASK_PRIORITY
471 //! Changes priority of the task grop
472 void set_priority ( priority_t );
474 //! Retrieves current priority of the current task group
475 priority_t priority () const;
476 #endif /* TBB_PREVIEW_TASK_PRIORITY */
479 //! Out-of-line part of the constructor.
480 /** Singled out to ensure backward binary compatibility of the future versions. **/
481 void __TBB_EXPORTED_METHOD init ();
485 friend class internal::allocate_root_with_context_proxy;
487 static const kind_type binding_required = bound;
488 static const kind_type binding_completed = kind_type(bound+1);
489 static const kind_type detached = kind_type(binding_completed+1);
490 static const kind_type dying = kind_type(detached+1);
492 //! Propagates state change (if any) from an ancestor
493 /** Checks if one of this object's ancestors is in a new state, and propagates
494 the new state to all its descendants in this object's heritage line. **/
495 template <typename T>
496 void propagate_state_from_ancestors ( T task_group_context::*mptr_state, T new_state );
498 //! Makes sure that the context is registered with a scheduler instance.
499 inline void finish_initialization ( internal::generic_scheduler *local_sched );
501 //! Registers this context with the local scheduler and binds it to its parent context
502 void bind_to ( internal::generic_scheduler *local_sched );
504 //! Registers this context with the local scheduler
505 void register_with ( internal::generic_scheduler *local_sched );
507 }; // class task_group_context
509 #endif /* __TBB_TASK_GROUP_CONTEXT */
511 //! Base class for user-defined tasks.
512 /** @ingroup task_scheduling */
513 class task: __TBB_TASK_BASE_ACCESS interface5::internal::task_base {
515 //! Set reference count
516 void __TBB_EXPORTED_METHOD internal_set_ref_count( int count );
518 //! Decrement reference count and return its new value.
519 internal::reference_count __TBB_EXPORTED_METHOD internal_decrement_ref_count();
522 //! Default constructor.
523 task() {prefix().extra_state=1;}
529 //! Should be overridden by derived classes.
530 virtual task* execute() = 0;
532 //! Enumeration of task states that the scheduler considers.
534 //! task is running, and will be destroyed after method execute() completes.
536 //! task to be rescheduled.
538 //! task is in ready pool, or is going to be put there, or was just taken off.
540 //! task object is freshly allocated or recycled.
542 //! task object is on free list, or is going to be put there, or was just taken off.
544 //! task to be recycled as continuation
548 //------------------------------------------------------------------------
550 //------------------------------------------------------------------------
552 //! Returns proxy for overloaded new that allocates a root task.
553 static internal::allocate_root_proxy allocate_root() {
554 return internal::allocate_root_proxy();
557 #if __TBB_TASK_GROUP_CONTEXT
558 //! Returns proxy for overloaded new that allocates a root task associated with user supplied context.
559 static internal::allocate_root_with_context_proxy allocate_root( task_group_context& ctx ) {
560 return internal::allocate_root_with_context_proxy(ctx);
562 #endif /* __TBB_TASK_GROUP_CONTEXT */
564 //! Returns proxy for overloaded new that allocates a continuation task of *this.
565 /** The continuation's parent becomes the parent of *this. */
566 internal::allocate_continuation_proxy& allocate_continuation() {
567 return *reinterpret_cast<internal::allocate_continuation_proxy*>(this);
570 //! Returns proxy for overloaded new that allocates a child task of *this.
571 internal::allocate_child_proxy& allocate_child() {
572 return *reinterpret_cast<internal::allocate_child_proxy*>(this);
575 //! Define recommended static form via import from base class.
576 using task_base::allocate_additional_child_of;
578 #if __TBB_DEPRECATED_TASK_INTERFACE
580 /** Usually, calling this method is unnecessary, because a task is
581 implicitly deleted after its execute() method runs. However,
582 sometimes a task needs to be explicitly deallocated, such as
583 when a root task is used as the parent in spawn_and_wait_for_all. */
584 void __TBB_EXPORTED_METHOD destroy( task& t );
585 #else /* !__TBB_DEPRECATED_TASK_INTERFACE */
586 //! Define recommended static form via import from base class.
587 using task_base::destroy;
588 #endif /* !__TBB_DEPRECATED_TASK_INTERFACE */
590 //------------------------------------------------------------------------
591 // Recycling of tasks
592 //------------------------------------------------------------------------
594 //! Change this to be a continuation of its former self.
595 /** The caller must guarantee that the task's refcount does not become zero until
596 after the method execute() returns. Typically, this is done by having
597 method execute() return a pointer to a child of the task. If the guarantee
598 cannot be made, use method recycle_as_safe_continuation instead.
600 Because of the hazard, this method may be deprecated in the future. */
601 void recycle_as_continuation() {
602 __TBB_ASSERT( prefix().state==executing, "execute not running?" );
603 prefix().state = allocated;
606 //! Recommended to use, safe variant of recycle_as_continuation
607 /** For safety, it requires additional increment of ref_count.
608 With no decendants and ref_count of 1, it has the semantics of recycle_to_reexecute. */
609 void recycle_as_safe_continuation() {
610 __TBB_ASSERT( prefix().state==executing, "execute not running?" );
611 prefix().state = recycle;
614 //! Change this to be a child of new_parent.
615 void recycle_as_child_of( task& new_parent ) {
616 internal::task_prefix& p = prefix();
617 __TBB_ASSERT( prefix().state==executing||prefix().state==allocated, "execute not running, or already recycled" );
618 __TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled as a child" );
619 __TBB_ASSERT( p.parent==NULL, "parent must be null" );
620 __TBB_ASSERT( new_parent.prefix().state<=recycle, "corrupt parent's state" );
621 __TBB_ASSERT( new_parent.prefix().state!=freed, "parent already freed" );
623 p.parent = &new_parent;
624 #if __TBB_TASK_GROUP_CONTEXT
625 p.context = new_parent.prefix().context;
626 #endif /* __TBB_TASK_GROUP_CONTEXT */
629 //! Schedule this for reexecution after current execute() returns.
630 /** Made obsolete by recycle_as_safe_continuation; may become deprecated. */
631 void recycle_to_reexecute() {
632 __TBB_ASSERT( prefix().state==executing, "execute not running, or already recycled" );
633 __TBB_ASSERT( prefix().ref_count==0, "no child tasks allowed when recycled for reexecution" );
634 prefix().state = reexecute;
637 // All depth-related methods are obsolete, and are retained for the sake
638 // of backward source compatibility only
639 intptr_t depth() const {return 0;}
640 void set_depth( intptr_t ) {}
641 void add_to_depth( int ) {}
644 //------------------------------------------------------------------------
645 // Spawning and blocking
646 //------------------------------------------------------------------------
648 //! Set reference count
649 void set_ref_count( int count ) {
650 #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
651 internal_set_ref_count(count);
653 prefix().ref_count = count;
654 #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
657 //! Atomically increment reference count and returns its old value.
658 /** Has acquire semantics */
659 void increment_ref_count() {
660 __TBB_FetchAndIncrementWacquire( &prefix().ref_count );
663 //! Atomically decrement reference count and returns its new value.
664 /** Has release semantics. */
665 int decrement_ref_count() {
666 #if TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT
667 return int(internal_decrement_ref_count());
669 return int(__TBB_FetchAndDecrementWrelease( &prefix().ref_count ))-1;
670 #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
673 //! Define recommended static forms via import from base class.
674 using task_base::spawn;
676 //! Similar to spawn followed by wait_for_all, but more efficient.
677 void spawn_and_wait_for_all( task& child ) {
678 prefix().owner->wait_for_all( *this, &child );
681 //! Similar to spawn followed by wait_for_all, but more efficient.
682 void __TBB_EXPORTED_METHOD spawn_and_wait_for_all( task_list& list );
684 //! Spawn task allocated by allocate_root, wait for it to complete, and deallocate it.
685 static void spawn_root_and_wait( task& root ) {
686 root.prefix().owner->spawn_root_and_wait( root, root.prefix().next );
689 //! Spawn root tasks on list and wait for all of them to finish.
690 /** If there are more tasks than worker threads, the tasks are spawned in
691 order of front to back. */
692 static void spawn_root_and_wait( task_list& root_list );
694 //! Wait for reference count to become one, and set reference count to zero.
695 /** Works on tasks while waiting. */
696 void wait_for_all() {
697 prefix().owner->wait_for_all( *this, NULL );
700 //! Enqueue task for starvation-resistant execution.
701 #if TBB_PREVIEW_TASK_PRIORITY
702 /** The task will be enqueued on the normal priority level disregarding the
703 priority of its task group.
705 The rationale of such semantics is that priority of an enqueued task is
706 statically fixed at the moment of its enqueuing, while task group priority
707 is dynamic. Thus automatic priority inheritance would be generally a subject
708 to the race, which may result in unexpected behavior.
710 Use enqueue() overload with explicit priority value and task::group_priority()
711 method to implement such priority inheritance when it is really necessary. **/
712 #endif /* TBB_PREVIEW_TASK_PRIORITY */
713 static void enqueue( task& t ) {
714 t.prefix().owner->enqueue( t, NULL );
717 #if TBB_PREVIEW_TASK_PRIORITY
718 //! Enqueue task for starvation-resistant execution on the specified priority level.
719 static void enqueue( task& t, priority_t p ) {
720 __TBB_ASSERT( p == priority_low || p == priority_normal || p == priority_high, "Invalid priority level value" );
721 t.prefix().owner->enqueue( t, (void*)p );
723 #endif /* TBB_PREVIEW_TASK_PRIORITY */
725 //! The innermost task being executed or destroyed by the current thread at the moment.
726 static task& __TBB_EXPORTED_FUNC self();
728 //! task on whose behalf this task is working, or NULL if this is a root.
729 task* parent() const {return prefix().parent;}
731 #if __TBB_TASK_GROUP_CONTEXT
732 //! This method is deprecated and will be removed in the future.
733 /** Use method group() instead. **/
734 task_group_context* context() {return prefix().context;}
736 //! Pointer to the task group descriptor.
737 task_group_context* group () { return prefix().context; }
738 #endif /* __TBB_TASK_GROUP_CONTEXT */
740 //! True if task was stolen from the task pool of another thread.
741 bool is_stolen_task() const {
742 return (prefix().extra_state & 0x80)!=0;
745 //------------------------------------------------------------------------
747 //------------------------------------------------------------------------
749 //! Current execution state
750 state_type state() const {return state_type(prefix().state);}
752 //! The internal reference count.
753 int ref_count() const {
755 internal::reference_count ref_count_ = prefix().ref_count;
756 __TBB_ASSERT( ref_count_==int(ref_count_), "integer overflow error");
758 return int(prefix().ref_count);
761 //! Obsolete, and only retained for the sake of backward compatibility. Always returns true.
762 bool __TBB_EXPORTED_METHOD is_owned_by_current_thread() const;
764 //------------------------------------------------------------------------
766 //------------------------------------------------------------------------
768 //! An id as used for specifying affinity.
769 /** Guaranteed to be integral type. Value of 0 means no affinity. */
770 typedef internal::affinity_id affinity_id;
772 //! Set affinity for this task.
773 void set_affinity( affinity_id id ) {prefix().affinity = id;}
775 //! Current affinity of this task
776 affinity_id affinity() const {return prefix().affinity;}
778 //! Invoked by scheduler to notify task that it ran on unexpected thread.
779 /** Invoked before method execute() runs, if task is stolen, or task has
780 affinity but will be executed on another thread.
782 The default action does nothing. */
783 virtual void __TBB_EXPORTED_METHOD note_affinity( affinity_id id );
785 #if __TBB_TASK_GROUP_CONTEXT
786 //! Moves this task from its current group into another one.
787 /** Argument ctx specifies the new group.
789 The primary purpose of this method is to associate unique task group context
790 with a task allocated for subsequent enqueuing. In contrast to spawned tasks
791 enqueued ones normally outlive the scope where they were created. This makes
792 traditional usage model where task group context are allocated locally on
793 the stack inapplicable. Dynamic allocation of context objects is performance
794 inefficient. Method change_group() allows to make task group context object
795 a member of the task class, and then associate it with its containing task
796 object in the latter's constructor. **/
797 void __TBB_EXPORTED_METHOD change_group ( task_group_context& ctx );
799 //! Initiates cancellation of all tasks in this cancellation group and its subordinate groups.
800 /** \return false if cancellation has already been requested, true otherwise. **/
801 bool cancel_group_execution () { return prefix().context->cancel_group_execution(); }
803 //! Returns true if the context has received cancellation request.
804 bool is_cancelled () const { return prefix().context->is_group_execution_cancelled(); }
805 #endif /* __TBB_TASK_GROUP_CONTEXT */
807 #if TBB_PREVIEW_TASK_PRIORITY
808 //! Changes priority of the task group this task belongs to.
809 void set_group_priority ( priority_t p ) { prefix().context->set_priority(p); }
811 //! Retrieves current priority of the task group this task belongs to.
812 priority_t group_priority () const { return prefix().context->priority(); }
814 #endif /* TBB_PREVIEW_TASK_PRIORITY */
817 friend class interface5::internal::task_base;
818 friend class task_list;
819 friend class internal::scheduler;
820 friend class internal::allocate_root_proxy;
821 #if __TBB_TASK_GROUP_CONTEXT
822 friend class internal::allocate_root_with_context_proxy;
823 #endif /* __TBB_TASK_GROUP_CONTEXT */
824 friend class internal::allocate_continuation_proxy;
825 friend class internal::allocate_child_proxy;
826 friend class internal::allocate_additional_child_of_proxy;
828 //! Get reference to corresponding task_prefix.
829 /** Version tag prevents loader on Linux from using the wrong symbol in debug builds. **/
830 internal::task_prefix& prefix( internal::version_tag* = NULL ) const {
831 return reinterpret_cast<internal::task_prefix*>(const_cast<task*>(this))[-1];
835 //! task that does nothing. Useful for synchronization.
836 /** @ingroup task_scheduling */
837 class empty_task: public task {
838 /*override*/ task* execute() {
843 //! A list of children.
844 /** Used for method task::spawn_children
845 @ingroup task_scheduling */
846 class task_list: internal::no_copy {
851 friend class interface5::internal::task_base;
853 //! Construct empty list
854 task_list() : first(NULL), next_ptr(&first) {}
856 //! Destroys the list, but does not destroy the task objects.
859 //! True if list if empty; false otherwise.
860 bool empty() const {return !first;}
862 //! Push task onto back of list.
863 void push_back( task& task ) {
864 task.prefix().next = NULL;
866 next_ptr = &task.prefix().next;
869 //! Pop the front task from the list.
871 __TBB_ASSERT( !empty(), "attempt to pop item from empty task_list" );
872 task* result = first;
873 first = result->prefix().next;
874 if( !first ) next_ptr = &first;
885 inline void interface5::internal::task_base::spawn( task& t ) {
886 t.prefix().owner->spawn( t, t.prefix().next );
889 inline void interface5::internal::task_base::spawn( task_list& list ) {
890 if( task* t = list.first ) {
891 t->prefix().owner->spawn( *t, *list.next_ptr );
896 inline void task::spawn_root_and_wait( task_list& root_list ) {
897 if( task* t = root_list.first ) {
898 t->prefix().owner->spawn_root_and_wait( *t, *root_list.next_ptr );
905 inline void *operator new( size_t bytes, const tbb::internal::allocate_root_proxy& ) {
906 return &tbb::internal::allocate_root_proxy::allocate(bytes);
909 inline void operator delete( void* task, const tbb::internal::allocate_root_proxy& ) {
910 tbb::internal::allocate_root_proxy::free( *static_cast<tbb::task*>(task) );
913 #if __TBB_TASK_GROUP_CONTEXT
914 inline void *operator new( size_t bytes, const tbb::internal::allocate_root_with_context_proxy& p ) {
915 return &p.allocate(bytes);
918 inline void operator delete( void* task, const tbb::internal::allocate_root_with_context_proxy& p ) {
919 p.free( *static_cast<tbb::task*>(task) );
921 #endif /* __TBB_TASK_GROUP_CONTEXT */
923 inline void *operator new( size_t bytes, const tbb::internal::allocate_continuation_proxy& p ) {
924 return &p.allocate(bytes);
927 inline void operator delete( void* task, const tbb::internal::allocate_continuation_proxy& p ) {
928 p.free( *static_cast<tbb::task*>(task) );
931 inline void *operator new( size_t bytes, const tbb::internal::allocate_child_proxy& p ) {
932 return &p.allocate(bytes);
935 inline void operator delete( void* task, const tbb::internal::allocate_child_proxy& p ) {
936 p.free( *static_cast<tbb::task*>(task) );
939 inline void *operator new( size_t bytes, const tbb::internal::allocate_additional_child_of_proxy& p ) {
940 return &p.allocate(bytes);
943 inline void operator delete( void* task, const tbb::internal::allocate_additional_child_of_proxy& p ) {
944 p.free( *static_cast<tbb::task*>(task) );
947 #endif /* __TBB_task_H */