Intel(R) Threading Building Blocks Doxygen Documentation  version 4.2.3
arena.h
Go to the documentation of this file.
1 /*
2  Copyright (c) 2005-2018 Intel Corporation
3 
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7 
8  http://www.apache.org/licenses/LICENSE-2.0
9 
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 
16 
17 
18 
19 */
20 
21 #ifndef _TBB_arena_H
22 #define _TBB_arena_H
23 
24 #include "tbb/tbb_stddef.h"
25 #include "tbb/atomic.h"
26 
27 #include "tbb/tbb_machine.h"
28 
29 #include "scheduler_common.h"
30 #include "intrusive_list.h"
31 #include "task_stream.h"
32 #include "../rml/include/rml_tbb.h"
33 #include "mailbox.h"
34 #include "observer_proxy.h"
35 #include "market.h"
36 #include "governor.h"
37 #include "concurrent_monitor.h"
38 
39 namespace tbb {
40 
41 class task_group_context;
42 class allocate_root_with_context_proxy;
43 
44 namespace internal {
45 
47 
49 struct arena_base : padded<intrusive_list_node> {
51  unsigned my_num_workers_allotted; // heavy use in stealing loop
52 
54 
57  atomic<unsigned> my_references; // heavy use in stealing loop
58 
59 #if __TBB_TASK_PRIORITY
60  volatile intptr_t my_top_priority; // heavy use in stealing loop
62 #endif /* !__TBB_TASK_PRIORITY */
63 
65  atomic<unsigned> my_limit; // heavy use in stealing loop
66 
68 
73  task_stream<num_priority_levels> my_task_stream; // heavy use in stealing loop
74 
77 
80 
82 
87 
88 #if __TBB_ARENA_OBSERVER
89  observer_list my_observers;
91 #endif
92 
93 #if __TBB_TASK_PRIORITY
94  intptr_t my_bottom_priority;
96 
98 
100  uintptr_t my_reload_epoch;
101 
103  task* my_orphaned_tasks;
104 
106  tbb::atomic<uintptr_t> my_abandonment_epoch;
107 
109 
112  tbb::atomic<intptr_t> my_skipped_fifo_priority;
113 #endif /* !__TBB_TASK_PRIORITY */
114 
115  // Below are rarely modified members
116 
119 
121  uintptr_t my_aba_epoch;
122 
123 #if !__TBB_FP_CONTEXT
126 #endif
127 
128 #if __TBB_TASK_GROUP_CONTEXT
129 
132  task_group_context* my_default_ctx;
133 #endif /* __TBB_TASK_GROUP_CONTEXT */
134 
136  unsigned my_num_slots;
137 
140 
141 #if __TBB_ENQUEUE_ENFORCED_CONCURRENCY
142  enum concurrency_mode {
144  cm_normal = 0, // arena is served by workers as usual
145  cm_enforced_local, // arena needs an extra worker despite the arena limit
146  cm_enforced_global // arena needs an extra worker despite a global limit
147  };
148 
150  concurrency_mode my_concurrency_mode;
151 #endif /* __TBB_ENQUEUE_ENFORCED_CONCURRENCY */
152 
155 
156 #if TBB_USE_ASSERT
157  uintptr_t my_guard;
159 #endif /* TBB_USE_ASSERT */
160 }; // struct arena_base
161 
162 class arena: public padded<arena_base>
163 {
166 public:
168 
174  };
175 
177  arena ( market&, unsigned max_num_workers, unsigned num_reserved_slots );
178 
180  static arena& allocate_arena( market&, unsigned num_slots, unsigned num_reserved_slots );
181 
182  static int unsigned num_arena_slots ( unsigned num_slots ) {
183  return max(2u, num_slots);
184  }
185 
186  static int allocation_size ( unsigned num_slots ) {
187  return sizeof(base_type) + num_slots * (sizeof(mail_outbox) + sizeof(arena_slot));
188  }
189 
192  __TBB_ASSERT( 0<id, "affinity id must be positive integer" );
193  __TBB_ASSERT( id <= my_num_slots, "affinity id out of bounds" );
194 
195  return ((mail_outbox*)this)[-(int)id];
196  }
197 
199  void free_arena ();
200 
201  typedef uintptr_t pool_state_t;
202 
204  static const pool_state_t SNAPSHOT_EMPTY = 0;
205 
208 
210  static const unsigned ref_external_bits = 12; // up to 4095 external and 1M workers
211 
213  static const unsigned ref_external = 1;
214  static const unsigned ref_worker = 1<<ref_external_bits;
215 
217  static bool is_busy_or_empty( pool_state_t s ) { return s < SNAPSHOT_FULL; }
218 
220  unsigned num_workers_active( ) {
222  }
223 
225  template<arena::new_work_type work_type> void advertise_new_work();
226 
228 
229  bool is_out_of_work();
230 
232  void enqueue_task( task&, intptr_t, FastRandom & );
233 
235  void process( generic_scheduler& );
236 
238  template<unsigned ref_param>
239  inline void on_thread_leaving ( );
240 
241 #if __TBB_STATISTICS
242  void dump_arena_statistics ();
244 #endif /* __TBB_STATISTICS */
245 
246 #if __TBB_TASK_PRIORITY
247 
249  inline bool may_have_tasks ( generic_scheduler*, bool& tasks_present, bool& dequeuing_possible );
250 
252  void orphan_offloaded_tasks ( generic_scheduler& s );
253 #endif /* __TBB_TASK_PRIORITY */
254 
255 #if __TBB_COUNT_TASK_NODES
256  intptr_t workers_task_node_count();
258 #endif
259 
261  bool has_enqueued_tasks();
262 
263 #if __TBB_ENQUEUE_ENFORCED_CONCURRENCY
264  bool recall_by_mandatory_request() const {
266  return my_market->my_mandatory_num_requested && my_concurrency_mode==cm_normal;
267  }
268 
270  bool must_have_concurrency() const {
271  return my_num_workers_requested &&
272  ( my_concurrency_mode==cm_enforced_local || my_concurrency_mode==cm_enforced_global );
273  }
274 #endif
275  static const size_t out_of_arena = ~size_t(0);
277  template <bool as_worker>
280  size_t occupy_free_slot_in_range( generic_scheduler& s, size_t lower, size_t upper );
281 
284 }; // class arena
285 
286 template<unsigned ref_param>
287 inline void arena::on_thread_leaving ( ) {
288  //
289  // Implementation of arena destruction synchronization logic contained various
290  // bugs/flaws at the different stages of its evolution, so below is a detailed
291  // description of the issues taken into consideration in the framework of the
292  // current design.
293  //
294  // In case of using fire-and-forget tasks (scheduled via task::enqueue())
295  // master thread is allowed to leave its arena before all its work is executed,
296  // and market may temporarily revoke all workers from this arena. Since revoked
297  // workers never attempt to reset arena state to EMPTY and cancel its request
298  // to RML for threads, the arena object is destroyed only when both the last
299  // thread is leaving it and arena's state is EMPTY (that is its master thread
300  // left and it does not contain any work).
301  // Thus resetting arena to EMPTY state (as earlier TBB versions did) should not
302  // be done here (or anywhere else in the master thread to that matter); doing so
303  // can result either in arena's premature destruction (at least without
304  // additional costly checks in workers) or in unnecessary arena state changes
305  // (and ensuing workers migration).
306  //
307  // A worker that checks for work presence and transitions arena to the EMPTY
308  // state (in snapshot taking procedure arena::is_out_of_work()) updates
309  // arena::my_pool_state first and only then arena::my_num_workers_requested.
310  // So the check for work absence must be done against the latter field.
311  //
312  // In a time window between decrementing the active threads count and checking
313  // if there is an outstanding request for workers. New worker thread may arrive,
314  // finish remaining work, set arena state to empty, and leave decrementing its
315  // refcount and destroying. Then the current thread will destroy the arena
316  // the second time. To preclude it a local copy of the outstanding request
317  // value can be stored before decrementing active threads count.
318  //
319  // But this technique may cause two other problem. When the stored request is
320  // zero, it is possible that arena still has threads and they can generate new
321  // tasks and thus re-establish non-zero requests. Then all the threads can be
322  // revoked (as described above) leaving this thread the last one, and causing
323  // it to destroy non-empty arena.
324  //
325  // The other problem takes place when the stored request is non-zero. Another
326  // thread may complete the work, set arena state to empty, and leave without
327  // arena destruction before this thread decrements the refcount. This thread
328  // cannot destroy the arena either. Thus the arena may be "orphaned".
329  //
330  // In both cases we cannot dereference arena pointer after the refcount is
331  // decremented, as our arena may already be destroyed.
332  //
333  // If this is the master thread, the market is protected by refcount to it.
334  // In case of workers market's liveness is ensured by the RML connection
335  // rundown protocol, according to which the client (i.e. the market) lives
336  // until RML server notifies it about connection termination, and this
337  // notification is fired only after all workers return into RML.
338  //
339  // Thus if we decremented refcount to zero we ask the market to check arena
340  // state (including the fact if it is alive) under the lock.
341  //
342  uintptr_t aba_epoch = my_aba_epoch;
343  market* m = my_market;
344  __TBB_ASSERT(my_references >= ref_param, "broken arena reference counter");
345 #if __TBB_STATISTICS_EARLY_DUMP
346  // While still holding a reference to the arena, compute how many external references are left.
347  // If just one, dump statistics.
348  if ( modulo_power_of_two(my_references,ref_worker)==ref_param ) // may only be true with ref_external
349  GATHER_STATISTIC( dump_arena_statistics() );
350 #endif
351 #if __TBB_ENQUEUE_ENFORCED_CONCURRENCY
352  // When there is no workers someone must free arena, as
353  // without workers, no one calls is_out_of_work().
354  // Skip workerless arenas because they have no demand for workers.
355  // TODO: consider more strict conditions for the cleanup,
356  // because it can create the demand of workers,
357  // but the arena can be already empty (and so ready for destroying)
358  if( ref_param==ref_external && my_num_slots != my_num_reserved_slots
359  && 0 == m->my_num_workers_soft_limit && my_concurrency_mode==cm_normal ) {
360  bool is_out = false;
361  for (int i=0; i<num_priority_levels; i++) {
362  is_out = is_out_of_work();
363  if (is_out)
364  break;
365  }
366  // We expect, that in worst case it's enough to have num_priority_levels-1
367  // calls to restore priorities and and yet another is_out_of_work() to conform
368  // that no work was found. But as market::set_active_num_workers() can be called
369  // concurrently, can't guarantee last is_out_of_work() return true.
370  }
371 #endif
372  if ( (my_references -= ref_param ) == 0 )
373  m->try_destroy_arena( this, aba_epoch );
374 }
375 
376 template<arena::new_work_type work_type> void arena::advertise_new_work() {
377  if( work_type == work_enqueued ) {
378 #if __TBB_ENQUEUE_ENFORCED_CONCURRENCY
380  if( my_concurrency_mode!=cm_enforced_global ) {
381  if( my_market->mandatory_concurrency_enable( this ) ) {
383  return;
384  }
385  }
386  } else if( my_max_num_workers==0 && my_num_reserved_slots==1 ) {
387  my_max_num_workers = 1;
388  __TBB_ASSERT(my_concurrency_mode==cm_normal, NULL);
389  my_concurrency_mode = cm_enforced_local;
391  my_market->adjust_demand( *this, 1 );
392  return;
393  }
394 #endif /* __TBB_ENQUEUE_ENFORCED_CONCURRENCY */
395  // Local memory fence here and below is required to avoid missed wakeups; see the comment below.
396  // Starvation resistant tasks require concurrency, so missed wakeups are unacceptable.
397  atomic_fence();
398  }
399  else if( work_type == wakeup ) {
400  __TBB_ASSERT(my_max_num_workers!=0, "Unexpected worker wakeup request");
401  atomic_fence();
402  }
403  // Double-check idiom that, in case of spawning, is deliberately sloppy about memory fences.
404  // Technically, to avoid missed wakeups, there should be a full memory fence between the point we
405  // released the task pool (i.e. spawned task) and read the arena's state. However, adding such a
406  // fence might hurt overall performance more than it helps, because the fence would be executed
407  // on every task pool release, even when stealing does not occur. Since TBB allows parallelism,
408  // but never promises parallelism, the missed wakeup is not a correctness problem.
409  pool_state_t snapshot = my_pool_state;
410  if( is_busy_or_empty(snapshot) ) {
411  // Attempt to mark as full. The compare_and_swap below is a little unusual because the
412  // result is compared to a value that can be different than the comparand argument.
414  if( snapshot!=SNAPSHOT_EMPTY ) {
415  // This thread read "busy" into snapshot, and then another thread transitioned
416  // my_pool_state to "empty" in the meantime, which caused the compare_and_swap above
417  // to fail. Attempt to transition my_pool_state from "empty" to "full".
419  // Some other thread transitioned my_pool_state from "empty", and hence became
420  // responsible for waking up workers.
421  return;
422  }
423  }
424  // This thread transitioned pool from empty to full state, and thus is responsible for
425  // telling the market that there is work to do.
426 #if __TBB_ENQUEUE_ENFORCED_CONCURRENCY
427  if( work_type == work_spawned ) {
428  if( my_concurrency_mode!=cm_normal ) {
429  switch( my_concurrency_mode ) {
430  case cm_enforced_local:
432  __TBB_ASSERT(!governor::local_scheduler()->is_worker(), "");
433  // There was deliberate oversubscription on 1 core for sake of starvation-resistant tasks.
434  // Now a single active thread (must be the master) supposedly starts a new parallel region
435  // with relaxed sequential semantics, and oversubscription should be avoided.
436  // Demand for workers has been decreased to 0 during SNAPSHOT_EMPTY, so just keep it.
437  my_max_num_workers = 0;
438  my_concurrency_mode = cm_normal;
439  break;
440  case cm_enforced_global:
441  my_market->mandatory_concurrency_disable( this );
443  break;
444  default:
445  break;
446  }
447  return;
448  }
449  }
450 #endif /* __TBB_ENQUEUE_ENFORCED_CONCURRENCY */
452  }
453  }
454 }
455 
456 } // namespace internal
457 } // namespace tbb
458 
459 #endif /* _TBB_arena_H */
Class representing where mail is put.
Definition: mailbox.h:100
unsigned my_max_num_workers
The number of workers requested by the master thread owning the arena.
Definition: arena.h:76
void on_thread_leaving()
Notification that worker or master leaves its arena.
Definition: arena.h:287
int my_num_workers_requested
The number of workers that are currently requested from the resource manager.
Definition: arena.h:79
Pads type T to fill out to a multiple of cache line size.
Definition: tbb_stddef.h:265
static int allocation_size(unsigned num_slots)
Definition: arena.h:186
The structure of an arena, except the array of slots.
Definition: arena.h:49
A fast random number generator.
Definition: tbb_misc.h:134
Base class for user-defined tasks.
Definition: task.h:576
Work stealing task scheduler.
Definition: scheduler.h:115
void const char const char int ITT_FORMAT __itt_group_sync s
market * my_market
The market that owns this arena.
Definition: arena.h:118
static const pool_state_t SNAPSHOT_FULL
At least one task has been offered for stealing since the last snapshot started.
Definition: arena.h:207
static const intptr_t num_priority_levels
void free_arena()
Completes arena shutdown, destructs and deallocates it.
Definition: arena.cpp:246
new_work_type
Types of work advertised by advertise_new_work()
Definition: arena.h:170
padded< arena_base > base_type
Definition: arena.h:167
bool has_enqueued_tasks()
Check for the presence of enqueued tasks at all priority levels.
Definition: arena.cpp:369
unsigned num_workers_active()
The number of workers active in the arena.
Definition: arena.h:220
#define __TBB_ASSERT(predicate, comment)
No-op version of __TBB_ASSERT.
Definition: tbb_stddef.h:169
void try_destroy_arena(arena *, uintptr_t aba_epoch)
Removes the arena from the market's list.
Definition: market.cpp:322
bool is_out_of_work()
Check if there is job anywhere in arena.
Definition: arena.cpp:397
static const size_t out_of_arena
Definition: arena.h:275
static int unsigned num_arena_slots(unsigned num_slots)
Definition: arena.h:182
void process(generic_scheduler &)
Registers the worker with the arena and enters TBB scheduler dispatch loop.
Definition: arena.cpp:106
void adjust_demand(arena &, int delta)
Request that arena's need in workers should be adjusted.
Definition: market.cpp:590
static generic_scheduler * local_scheduler()
Obtain the thread-local instance of the TBB scheduler.
Definition: governor.h:126
static const unsigned ref_external
Reference increment values for externals and workers.
Definition: arena.h:213
static const pool_state_t SNAPSHOT_EMPTY
No tasks to steal since last snapshot was taken.
Definition: arena.h:204
static arena & allocate_arena(market &, unsigned num_slots, unsigned num_reserved_slots)
Allocate an instance of arena.
Definition: arena.cpp:235
Used to form groups of tasks.
Definition: task.h:319
unsigned my_num_workers_allotted
The number of workers that have been marked out by the resource manager to service the arena.
Definition: arena.h:51
size_t occupy_free_slot(generic_scheduler &s)
Tries to occupy a slot in the arena. On success, returns the slot index; if no slot is available,...
Definition: arena.cpp:90
uintptr_t pool_state_t
Definition: arena.h:201
T max(const T &val1, const T &val2)
Utility template function returning greater of the two values.
Definition: tbb_misc.h:118
unsigned my_num_workers_soft_limit
Current application-imposed limit on the number of workers (see set_active_num_workers())
Definition: market.h:82
task_stream< num_priority_levels > my_task_stream
Task pool for the tasks scheduled via task::enqueue() method.
Definition: arena.h:73
void advertise_new_work()
If necessary, raise a flag that there is new job in arena.
Definition: arena.h:376
atomic< unsigned > my_limit
The maximal number of currently busy slots.
Definition: arena.h:65
value_type compare_and_swap(value_type value, value_type comparand)
Definition: atomic.h:289
void restore_priority_if_need()
If enqueued tasks found, restore arena priority and task presence status.
Definition: arena.cpp:377
The graph class.
unsigned my_num_reserved_slots
The number of reserved slots (can be occupied only by masters).
Definition: arena.h:139
static bool is_busy_or_empty(pool_state_t s)
No tasks to steal or snapshot is being taken.
Definition: arena.h:217
static const unsigned ref_worker
Definition: arena.h:214
unsigned short affinity_id
An id as used for specifying affinity.
Definition: task.h:122
unsigned my_num_slots
The number of slots in the arena.
Definition: arena.h:136
cpu_ctl_env my_cpu_ctl_env
FPU control settings of arena's master thread captured at the moment of arena instantiation.
Definition: arena.h:125
atomic< unsigned > my_references
Reference counter for the arena.
Definition: arena.h:57
tbb::atomic< uintptr_t > my_pool_state
Current task pool state and estimate of available tasks amount.
Definition: arena.h:86
void const char const char int ITT_FORMAT __itt_group_sync x void const char ITT_FORMAT __itt_group_sync s void ITT_FORMAT __itt_group_sync p void ITT_FORMAT p void ITT_FORMAT p no args __itt_suppress_mode_t unsigned int void size_t ITT_FORMAT d void ITT_FORMAT p void ITT_FORMAT p __itt_model_site __itt_model_site_instance ITT_FORMAT p __itt_model_task __itt_model_task_instance ITT_FORMAT p void ITT_FORMAT p void ITT_FORMAT p void size_t ITT_FORMAT d void ITT_FORMAT p const wchar_t ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s const char ITT_FORMAT s no args void ITT_FORMAT p size_t ITT_FORMAT d no args const wchar_t const wchar_t ITT_FORMAT s __itt_heap_function void size_t int ITT_FORMAT d __itt_heap_function void ITT_FORMAT p __itt_heap_function void void size_t int ITT_FORMAT d no args no args unsigned int ITT_FORMAT u const __itt_domain __itt_id ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain __itt_id ITT_FORMAT p const __itt_domain __itt_id __itt_timestamp __itt_timestamp ITT_FORMAT lu const __itt_domain __itt_id __itt_id __itt_string_handle ITT_FORMAT p const __itt_domain ITT_FORMAT p const __itt_domain __itt_string_handle unsigned long long ITT_FORMAT lu const __itt_domain __itt_id __itt_string_handle __itt_metadata_type size_t void ITT_FORMAT p const __itt_domain __itt_id __itt_string_handle const wchar_t size_t ITT_FORMAT lu const __itt_domain __itt_id __itt_relation __itt_id ITT_FORMAT p const wchar_t int ITT_FORMAT __itt_group_mark d int
arena(market &, unsigned max_num_workers, unsigned num_reserved_slots)
Constructor.
Definition: arena.cpp:190
static const unsigned ref_external_bits
The number of least significant bits for external references.
Definition: arena.h:210
void atomic_fence()
Sequentially consistent full memory fence.
Definition: tbb_machine.h:343
mail_outbox & mailbox(affinity_id id)
Get reference to mailbox corresponding to given affinity_id.
Definition: arena.h:191
size_t occupy_free_slot_in_range(generic_scheduler &s, size_t lower, size_t upper)
Tries to occupy a slot in the specified range.
Definition: arena.cpp:75
argument_integer_type modulo_power_of_two(argument_integer_type arg, divisor_integer_type divisor)
A function to compute arg modulo divisor where divisor is a power of 2.
Definition: tbb_stddef.h:365
uintptr_t my_aba_epoch
ABA prevention marker.
Definition: arena.h:121
concurrent_monitor my_exit_monitors
Waiting object for master threads that cannot join the arena.
Definition: arena.h:154
arena_slot my_slots[1]
Definition: arena.h:283
void enqueue_task(task &, intptr_t, FastRandom &)
enqueue a task into starvation-resistance queue
Definition: arena.cpp:544
#define GATHER_STATISTIC(x)

Copyright © 2005-2018 Intel Corporation. All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are registered trademarks or trademarks of Intel Corporation or its subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.