]> git.sesse.net Git - casparcg/blob - tbb/include/tbb/task.h
7b8dab85141b77a5df9202c460f01517f79cc816
[casparcg] / tbb / include / tbb / task.h
1 /*
2     Copyright 2005-2011 Intel Corporation.  All Rights Reserved.
3
4     This file is part of Threading Building Blocks.
5
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.
9
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.
14
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
18
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.
27 */
28
29 #ifndef __TBB_task_H
30 #define __TBB_task_H
31
32 #include "tbb_stddef.h"
33 #include "tbb_machine.h"
34 #include <climits>
35
36 typedef struct ___itt_caller *__itt_caller;
37
38 namespace tbb {
39
40 class task;
41 class task_list;
42
43 #if __TBB_TASK_GROUP_CONTEXT
44 class task_group_context;
45 #endif /* __TBB_TASK_GROUP_CONTEXT */
46
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
51 #else
52 #define __TBB_TASK_BASE_ACCESS private
53 #endif
54
55 namespace internal {
56
57     class allocate_additional_child_of_proxy: no_assign {
58         //! No longer used, but retained for binary layout compatibility.  Always NULL.
59         task* self;
60         task& parent;
61     public:
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;
65     };
66
67 }
68
69 namespace interface5 {
70     namespace internal {
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;
80
81             //! Schedule task for execution when a worker becomes available.
82             static void spawn( task& t );
83  
84             //! Spawn multiple tasks and clear list.
85             static void spawn( task_list& list );
86
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);
92             }
93
94             //! Destroy a task.
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 );
100         }; 
101     } // internal
102 } // interface5
103
104 //! @cond INTERNAL
105 namespace internal {
106
107     class scheduler: no_copy {
108     public:
109         //! For internal use only
110         virtual void spawn( task& first, task*& next ) = 0;
111
112         //! For internal use only
113         virtual void wait_for_all( task& parent, task* child ) = 0;
114
115         //! For internal use only
116         virtual void spawn_root_and_wait( task& first, task*& next ) = 0;
117
118         //! Pure virtual destructor;
119         //  Have to have it just to shut up overzealous compilation warnings
120         virtual ~scheduler() = 0;
121
122         //! For internal use only
123         virtual void enqueue( task& t, void* reserved ) = 0;
124     };
125
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;
129
130     //! An id as used for specifying affinity.
131     typedef unsigned short affinity_id;
132
133 #if __TBB_TASK_GROUP_CONTEXT
134     class generic_scheduler;
135
136     struct context_list_node_t {
137         context_list_node_t *my_prev,
138                             *my_next;
139     };
140
141     class allocate_root_with_context_proxy: no_assign {
142         task_group_context& my_context;
143     public:
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;
147     };
148 #endif /* __TBB_TASK_GROUP_CONTEXT */
149
150     class allocate_root_proxy: no_assign {
151     public:
152         static task& __TBB_EXPORTED_FUNC allocate( size_t size );
153         static void __TBB_EXPORTED_FUNC free( task& );
154     };
155
156     class allocate_continuation_proxy: no_assign {
157     public:
158         task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
159         void __TBB_EXPORTED_METHOD free( task& ) const;
160     };
161
162     class allocate_child_proxy: no_assign {
163     public:
164         task& __TBB_EXPORTED_METHOD allocate( size_t size ) const;
165         void __TBB_EXPORTED_METHOD free( task& ) const;
166     };
167
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 */
174     class task_prefix {
175     private:
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;
184
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()
189             methods. */
190         task_group_context  *context;
191 #endif /* __TBB_TASK_GROUP_CONTEXT */
192         
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. */
199         scheduler* origin;
200
201 #if TBB_PREVIEW_TASK_PRIORITY
202         union {
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. **/
207         scheduler* owner;
208
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;
213         };
214 #endif /* TBB_PREVIEW_TASK_PRIORITY */
215
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. */
220         tbb::task* parent;
221
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;
228
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. **/
232         int depth;
233
234         //! A task::state_type, stored as a byte for compactness.
235         /** This state is exposed to users via method task::state(). */
236         unsigned char state;
237
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
241             0x20 -> task_proxy
242             0x40 -> task has live ref_count
243             0x80 -> a stolen task */
244         unsigned char extra_state;
245
246         affinity_id affinity;
247
248         //! "next" field for list of task
249         tbb::task* next;
250
251         //! The task corresponding to this task_prefix.
252         tbb::task& task() {return *reinterpret_cast<tbb::task*>(this+1);}
253     };
254
255 } // namespace internal
256 //! @endcond
257
258 #if __TBB_TASK_GROUP_CONTEXT
259
260 #if TBB_PREVIEW_TASK_PRIORITY
261 namespace internal {
262     static const int priority_stride_v4 = INT_MAX / 4;
263 }
264
265 enum priority_t {
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
269 };
270
271 #endif /* TBB_PREVIEW_TASK_PRIORITY */
272
273 #if TBB_USE_CAPTURED_EXCEPTION
274     class tbb_exception;
275 #else
276     namespace internal {
277         class tbb_exception_ptr;
278     }
279 #endif /* !TBB_USE_CAPTURED_EXCEPTION */
280
281 class task_scheduler_init;
282
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). 
289
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.
294     
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.
299
300     IMPLEMENTATION NOTE: 
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 {
305 private:
306     friend class internal::generic_scheduler;
307     friend class task_scheduler_init;
308
309 #if TBB_USE_CAPTURED_EXCEPTION
310     typedef tbb_exception exception_container_type;
311 #else
312     typedef internal::tbb_exception_ptr exception_container_type;
313 #endif
314
315     enum version_traits_word_layout {
316         traits_offset = 16,
317         version_mask = 0xFFFF,
318         traits_mask = 0xFFFFul << traits_offset
319     };
320
321 public:
322     enum kind_type {
323         isolated,
324         bound
325     };
326
327     enum traits_type {
328         exact_exception = 0x0001ul << traits_offset,
329         concurrent_wait = 0x0004ul << traits_offset,
330 #if TBB_USE_CAPTURED_EXCEPTION
331         default_traits = 0
332 #else
333         default_traits = exact_exception
334 #endif /* !TBB_USE_CAPTURED_EXCEPTION */
335     };
336
337 private:
338     enum state {
339         may_have_children = 1
340     };
341
342     union {
343         //! Flavor of this context: bound or isolated.
344         kind_type my_kind;
345         uintptr_t _my_kind_aligner;
346     };
347
348     //! Pointer to the context of the parent cancellation group. NULL for isolated contexts.
349     task_group_context *my_parent;
350
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;
355
356     //! Used to set and maintain stack stitching point for Intel Performance Tools.
357     __itt_caller itt_caller;
358
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)];
366     
367     //! Specifies whether cancellation was request for this task group.
368     uintptr_t my_cancellation_requested;
369     
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;
375
376     //! Pointer to the container storing exception being propagated across this task group.
377     exception_container_type *my_exception;
378
379     //! Scheduler instance that registered this context in its thread specific list.
380     internal::generic_scheduler *my_owner;
381
382     //! Internal state (combination of state flags).
383     uintptr_t my_state;
384
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 */
389
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
394                             - sizeof(intptr_t)
395 #endif /* TBB_PREVIEW_TASK_PRIORITY */
396                           ];
397
398 public:
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.
405
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.
408         
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.
413         
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.
418         
419         VERSIONING NOTE: 
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.
424
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)
432     {
433         init();
434     }
435
436     __TBB_EXPORTED_METHOD ~task_group_context ();
437
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.
442         
443         IMPORTANT: This method is not thread safe!
444
445         The method does not change the context's parent if it is set. **/ 
446     void __TBB_EXPORTED_METHOD reset ();
447
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. 
450
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 ();
457
458     //! Returns true if the context received cancellation request.
459     bool __TBB_EXPORTED_METHOD is_group_execution_cancelled () const;
460
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 ();
469
470 #if TBB_PREVIEW_TASK_PRIORITY
471     //! Changes priority of the task grop 
472     void set_priority ( priority_t );
473
474     //! Retrieves current priority of the current task group
475     priority_t priority () const;
476 #endif /* TBB_PREVIEW_TASK_PRIORITY */
477
478 protected:
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 ();
482
483 private:
484     friend class task;
485     friend class internal::allocate_root_with_context_proxy;
486
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);
491
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 );
497
498     //! Makes sure that the context is registered with a scheduler instance.
499     inline void finish_initialization ( internal::generic_scheduler *local_sched );
500
501     //! Registers this context with the local scheduler and binds it to its parent context
502     void bind_to ( internal::generic_scheduler *local_sched );
503
504     //! Registers this context with the local scheduler
505     void register_with ( internal::generic_scheduler *local_sched );
506
507 }; // class task_group_context
508
509 #endif /* __TBB_TASK_GROUP_CONTEXT */
510
511 //! Base class for user-defined tasks.
512 /** @ingroup task_scheduling */
513 class task: __TBB_TASK_BASE_ACCESS interface5::internal::task_base {
514
515     //! Set reference count
516     void __TBB_EXPORTED_METHOD internal_set_ref_count( int count );
517
518     //! Decrement reference count and return its new value.
519     internal::reference_count __TBB_EXPORTED_METHOD internal_decrement_ref_count();
520
521 protected:
522     //! Default constructor.
523     task() {prefix().extra_state=1;}
524
525 public:
526     //! Destructor.
527     virtual ~task() {}
528
529     //! Should be overridden by derived classes.
530     virtual task* execute() = 0;
531
532     //! Enumeration of task states that the scheduler considers.
533     enum state_type {
534         //! task is running, and will be destroyed after method execute() completes.
535         executing,
536         //! task to be rescheduled.
537         reexecute,
538         //! task is in ready pool, or is going to be put there, or was just taken off.
539         ready,
540         //! task object is freshly allocated or recycled.
541         allocated,
542         //! task object is on free list, or is going to be put there, or was just taken off.
543         freed,
544         //! task to be recycled as continuation
545         recycle 
546     };
547
548     //------------------------------------------------------------------------
549     // Allocating tasks
550     //------------------------------------------------------------------------
551
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();
555     }
556
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);
561     }
562 #endif /* __TBB_TASK_GROUP_CONTEXT */
563
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);
568     }
569
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);
573     }
574
575     //! Define recommended static form via import from base class.
576     using task_base::allocate_additional_child_of;
577
578 #if __TBB_DEPRECATED_TASK_INTERFACE
579     //! Destroy a task.
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 */
589
590     //------------------------------------------------------------------------
591     // Recycling of tasks
592     //------------------------------------------------------------------------
593
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. 
599        
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;
604     }
605
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;
612     }
613
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" );
622         p.state = allocated;
623         p.parent = &new_parent;
624 #if __TBB_TASK_GROUP_CONTEXT
625         p.context = new_parent.prefix().context;
626 #endif /* __TBB_TASK_GROUP_CONTEXT */
627     }
628
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;
635     }
636
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 ) {}
642
643
644     //------------------------------------------------------------------------
645     // Spawning and blocking
646     //------------------------------------------------------------------------
647
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);
652 #else
653         prefix().ref_count = count;
654 #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
655     }
656
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 );
661     }
662
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());
668 #else
669         return int(__TBB_FetchAndDecrementWrelease( &prefix().ref_count ))-1;
670 #endif /* TBB_USE_THREADING_TOOLS||TBB_USE_ASSERT */
671     }
672
673     //! Define recommended static forms via import from base class.
674     using task_base::spawn;
675
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 );
679     }
680
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 );
683
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 );
687     }
688
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 );
693
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 );
698     }
699
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.
704         
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. 
709         
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 );
715     }
716
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 );
722     }
723 #endif /* TBB_PREVIEW_TASK_PRIORITY */
724
725     //! The innermost task being executed or destroyed by the current thread at the moment.
726     static task& __TBB_EXPORTED_FUNC self();
727
728     //! task on whose behalf this task is working, or NULL if this is a root.
729     task* parent() const {return prefix().parent;}
730
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;}
735
736     //! Pointer to the task group descriptor.
737     task_group_context* group () { return prefix().context; }
738 #endif /* __TBB_TASK_GROUP_CONTEXT */   
739
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;
743     }
744
745     //------------------------------------------------------------------------
746     // Debugging
747     //------------------------------------------------------------------------
748
749     //! Current execution state
750     state_type state() const {return state_type(prefix().state);}
751
752     //! The internal reference count.
753     int ref_count() const {
754 #if TBB_USE_ASSERT
755         internal::reference_count ref_count_ = prefix().ref_count;
756         __TBB_ASSERT( ref_count_==int(ref_count_), "integer overflow error");
757 #endif
758         return int(prefix().ref_count);
759     }
760
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;
763
764     //------------------------------------------------------------------------
765     // Affinity
766     //------------------------------------------------------------------------
767  
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;
771
772     //! Set affinity for this task.
773     void set_affinity( affinity_id id ) {prefix().affinity = id;}
774
775     //! Current affinity of this task
776     affinity_id affinity() const {return prefix().affinity;}
777
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. 
781
782         The default action does nothing. */
783     virtual void __TBB_EXPORTED_METHOD note_affinity( affinity_id id );
784
785 #if __TBB_TASK_GROUP_CONTEXT
786     //! Moves this task from its current group into another one.
787     /** Argument ctx specifies the new group.
788
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 );
798
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(); }
802
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 */
806
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); }
810
811     //! Retrieves current priority of the task group this task belongs to.
812     priority_t group_priority () const { return prefix().context->priority(); }
813
814 #endif /* TBB_PREVIEW_TASK_PRIORITY */
815
816 private:
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;
827     
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];
832     }
833 }; // class task
834
835 //! task that does nothing.  Useful for synchronization.
836 /** @ingroup task_scheduling */
837 class empty_task: public task {
838     /*override*/ task* execute() {
839         return NULL;
840     }
841 };
842
843 //! A list of children.
844 /** Used for method task::spawn_children
845     @ingroup task_scheduling */
846 class task_list: internal::no_copy {
847 private:
848     task* first;
849     task** next_ptr;
850     friend class task;
851     friend class interface5::internal::task_base;
852 public:
853     //! Construct empty list
854     task_list() : first(NULL), next_ptr(&first) {}
855
856     //! Destroys the list, but does not destroy the task objects.
857     ~task_list() {}
858
859     //! True if list if empty; false otherwise.
860     bool empty() const {return !first;}
861
862     //! Push task onto back of list.
863     void push_back( task& task ) {
864         task.prefix().next = NULL;
865         *next_ptr = &task;
866         next_ptr = &task.prefix().next;
867     }
868
869     //! Pop the front task from the list.
870     task& pop_front() {
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;
875         return *result;
876     }
877
878     //! Clear the list
879     void clear() {
880         first=NULL;
881         next_ptr=&first;
882     }
883 };
884
885 inline void interface5::internal::task_base::spawn( task& t ) {
886     t.prefix().owner->spawn( t, t.prefix().next );
887 }
888
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 );
892         list.clear();
893     }
894 }
895
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 );
899         root_list.clear();
900     }
901 }
902
903 } // namespace tbb
904
905 inline void *operator new( size_t bytes, const tbb::internal::allocate_root_proxy& ) {
906     return &tbb::internal::allocate_root_proxy::allocate(bytes);
907 }
908
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) );
911 }
912
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);
916 }
917
918 inline void operator delete( void* task, const tbb::internal::allocate_root_with_context_proxy& p ) {
919     p.free( *static_cast<tbb::task*>(task) );
920 }
921 #endif /* __TBB_TASK_GROUP_CONTEXT */
922
923 inline void *operator new( size_t bytes, const tbb::internal::allocate_continuation_proxy& p ) {
924     return &p.allocate(bytes);
925 }
926
927 inline void operator delete( void* task, const tbb::internal::allocate_continuation_proxy& p ) {
928     p.free( *static_cast<tbb::task*>(task) );
929 }
930
931 inline void *operator new( size_t bytes, const tbb::internal::allocate_child_proxy& p ) {
932     return &p.allocate(bytes);
933 }
934
935 inline void operator delete( void* task, const tbb::internal::allocate_child_proxy& p ) {
936     p.free( *static_cast<tbb::task*>(task) );
937 }
938
939 inline void *operator new( size_t bytes, const tbb::internal::allocate_additional_child_of_proxy& p ) {
940     return &p.allocate(bytes);
941 }
942
943 inline void operator delete( void* task, const tbb::internal::allocate_additional_child_of_proxy& p ) {
944     p.free( *static_cast<tbb::task*>(task) );
945 }
946
947 #endif /* __TBB_task_H */