taskqueue.hpp 27.5 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#ifndef SHARE_VM_UTILITIES_TASKQUEUE_HPP
#define SHARE_VM_UTILITIES_TASKQUEUE_HPP

#include "memory/allocation.hpp"
#include "memory/allocation.inline.hpp"
#include "runtime/mutex.hpp"
#include "utilities/stack.hpp"
#ifdef TARGET_OS_ARCH_linux_x86
# include "orderAccess_linux_x86.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_sparc
# include "orderAccess_linux_sparc.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_zero
# include "orderAccess_linux_zero.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_solaris_x86
# include "orderAccess_solaris_x86.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_solaris_sparc
# include "orderAccess_solaris_sparc.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_windows_x86
# include "orderAccess_windows_x86.inline.hpp"
#endif
50 51 52 53 54 55
#ifdef TARGET_OS_ARCH_linux_arm
# include "orderAccess_linux_arm.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_linux_ppc
# include "orderAccess_linux_ppc.inline.hpp"
#endif
N
never 已提交
56 57 58 59 60 61
#ifdef TARGET_OS_ARCH_bsd_x86
# include "orderAccess_bsd_x86.inline.hpp"
#endif
#ifdef TARGET_OS_ARCH_bsd_zero
# include "orderAccess_bsd_zero.inline.hpp"
#endif
62

J
jcoomes 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
// Simple TaskQueue stats that are collected by default in debug builds.

#if !defined(TASKQUEUE_STATS) && defined(ASSERT)
#define TASKQUEUE_STATS 1
#elif !defined(TASKQUEUE_STATS)
#define TASKQUEUE_STATS 0
#endif

#if TASKQUEUE_STATS
#define TASKQUEUE_STATS_ONLY(code) code
#else
#define TASKQUEUE_STATS_ONLY(code)
#endif // TASKQUEUE_STATS

#if TASKQUEUE_STATS
class TaskQueueStats {
public:
  enum StatId {
    push,             // number of taskqueue pushes
    pop,              // number of taskqueue pops
    pop_slow,         // subset of taskqueue pops that were done slow-path
    steal_attempt,    // number of taskqueue steal attempts
    steal,            // number of taskqueue steals
    overflow,         // number of overflow pushes
    overflow_max_len, // max length of overflow stack
    last_stat_id
  };

public:
  inline TaskQueueStats()       { reset(); }

  inline void record_push()     { ++_stats[push]; }
  inline void record_pop()      { ++_stats[pop]; }
  inline void record_pop_slow() { record_pop(); ++_stats[pop_slow]; }
  inline void record_steal(bool success);
  inline void record_overflow(size_t new_length);

100 101
  TaskQueueStats & operator +=(const TaskQueueStats & addend);

J
jcoomes 已提交
102 103 104 105 106
  inline size_t get(StatId id) const { return _stats[id]; }
  inline const size_t* get() const   { return _stats; }

  inline void reset();

107
  // Print the specified line of the header (does not include a line separator).
J
jcoomes 已提交
108 109
  static void print_header(unsigned int line, outputStream* const stream = tty,
                           unsigned int width = 10);
110
  // Print the statistics (does not include a line separator).
J
jcoomes 已提交
111 112
  void print(outputStream* const stream = tty, unsigned int width = 10) const;

113 114
  DEBUG_ONLY(void verify() const;)

J
jcoomes 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
private:
  size_t                    _stats[last_stat_id];
  static const char * const _names[last_stat_id];
};

void TaskQueueStats::record_steal(bool success) {
  ++_stats[steal_attempt];
  if (success) ++_stats[steal];
}

void TaskQueueStats::record_overflow(size_t new_len) {
  ++_stats[overflow];
  if (new_len > _stats[overflow_max_len]) _stats[overflow_max_len] = new_len;
}

void TaskQueueStats::reset() {
  memset(_stats, 0, sizeof(_stats));
}
#endif // TASKQUEUE_STATS

135 136
// TaskQueueSuper collects functionality common to all GenericTaskQueue instances.

Z
zgu 已提交
137 138
template <unsigned int N, MEMFLAGS F>
class TaskQueueSuper: public CHeapObj<F> {
D
duke 已提交
139
protected:
140 141 142 143
  // Internal type for indexing the queue; also used for the tag.
  typedef NOT_LP64(uint16_t) LP64_ONLY(uint32_t) idx_t;

  // The first free element after the last one pushed (mod N).
144
  volatile uint _bottom;
D
duke 已提交
145

146
  enum { MOD_N_MASK = N - 1 };
D
duke 已提交
147

148 149 150 151 152
  class Age {
  public:
    Age(size_t data = 0)         { _data = data; }
    Age(const Age& age)          { _data = age._data; }
    Age(idx_t top, idx_t tag)    { _fields._top = top; _fields._tag = tag; }
D
duke 已提交
153

154 155
    Age   get()        const volatile { return _data; }
    void  set(Age age) volatile       { _data = age._data; }
D
duke 已提交
156

157 158
    idx_t top()        const volatile { return _fields._top; }
    idx_t tag()        const volatile { return _fields._tag; }
D
duke 已提交
159

160 161 162 163 164
    // Increment top; if it wraps, increment tag also.
    void increment() {
      _fields._top = increment_index(_fields._top);
      if (_fields._top == 0) ++_fields._tag;
    }
D
duke 已提交
165

166 167 168 169
    Age cmpxchg(const Age new_age, const Age old_age) volatile {
      return (size_t) Atomic::cmpxchg_ptr((intptr_t)new_age._data,
                                          (volatile intptr_t *)&_data,
                                          (intptr_t)old_age._data);
D
duke 已提交
170
    }
171 172 173 174 175 176 177 178 179 180 181 182

    bool operator ==(const Age& other) const { return _data == other._data; }

  private:
    struct fields {
      idx_t _top;
      idx_t _tag;
    };
    union {
      size_t _data;
      fields _fields;
    };
D
duke 已提交
183 184
  };

185
  volatile Age _age;
D
duke 已提交
186

187 188 189
  // These both operate mod N.
  static uint increment_index(uint ind) {
    return (ind + 1) & MOD_N_MASK;
D
duke 已提交
190
  }
191 192
  static uint decrement_index(uint ind) {
    return (ind - 1) & MOD_N_MASK;
D
duke 已提交
193 194
  }

195 196
  // Returns a number in the range [0..N).  If the result is "N-1", it should be
  // interpreted as 0.
197
  uint dirty_size(uint bot, uint top) const {
198
    return (bot - top) & MOD_N_MASK;
D
duke 已提交
199 200 201
  }

  // Returns the size corresponding to the given "bot" and "top".
202
  uint size(uint bot, uint top) const {
203
    uint sz = dirty_size(bot, top);
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    // Has the queue "wrapped", so that bottom is less than top?  There's a
    // complicated special case here.  A pair of threads could perform pop_local
    // and pop_global operations concurrently, starting from a state in which
    // _bottom == _top+1.  The pop_local could succeed in decrementing _bottom,
    // and the pop_global in incrementing _top (in which case the pop_global
    // will be awarded the contested queue element.)  The resulting state must
    // be interpreted as an empty queue.  (We only need to worry about one such
    // event: only the queue owner performs pop_local's, and several concurrent
    // threads attempting to perform the pop_global will all perform the same
    // CAS, and only one can succeed.)  Any stealing thread that reads after
    // either the increment or decrement will see an empty queue, and will not
    // join the competitors.  The "sz == -1 || sz == N-1" state will not be
    // modified by concurrent queues, so the owner thread can reset the state to
    // _bottom == top so subsequent pushes will be performed normally.
    return (sz == N - 1) ? 0 : sz;
D
duke 已提交
219 220 221 222 223
  }

public:
  TaskQueueSuper() : _bottom(0), _age() {}

224 225 226
  // Return true if the TaskQueue contains/does not contain any tasks.
  bool peek()     const { return _bottom != _age.top(); }
  bool is_empty() const { return size() == 0; }
D
duke 已提交
227 228 229 230

  // Return an estimate of the number of elements in the queue.
  // The "careful" version admits the possibility of pop_local/pop_global
  // races.
231
  uint size() const {
232
    return size(_bottom, _age.top());
D
duke 已提交
233 234
  }

235
  uint dirty_size() const {
236
    return dirty_size(_bottom, _age.top());
D
duke 已提交
237 238
  }

239 240
  void set_empty() {
    _bottom = 0;
241
    _age.set(0);
242 243
  }

D
duke 已提交
244 245
  // Maximum number of elements allowed in the queue.  This is two less
  // than the actual queue size, for somewhat complicated reasons.
246
  uint max_elems() const { return N - 2; }
247 248 249

  // Total size of queue.
  static const uint total_size() { return N; }
J
jcoomes 已提交
250 251

  TASKQUEUE_STATS_ONLY(TaskQueueStats stats;)
D
duke 已提交
252 253
};

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
//
// GenericTaskQueue implements an ABP, Aurora-Blumofe-Plaxton, double-
// ended-queue (deque), intended for use in work stealing. Queue operations
// are non-blocking.
//
// A queue owner thread performs push() and pop_local() operations on one end
// of the queue, while other threads may steal work using the pop_global()
// method.
//
// The main difference to the original algorithm is that this
// implementation allows wrap-around at the end of its allocated
// storage, which is an array.
//
// The original paper is:
//
// Arora, N. S., Blumofe, R. D., and Plaxton, C. G.
// Thread scheduling for multiprogrammed multiprocessors.
// Theory of Computing Systems 34, 2 (2001), 115-144.
//
// The following paper provides an correctness proof and an
// implementation for weakly ordered memory models including (pseudo-)
// code containing memory barriers for a Chase-Lev deque. Chase-Lev is
// similar to ABP, with the main difference that it allows resizing of the
// underlying storage:
//
// Le, N. M., Pop, A., Cohen A., and Nardell, F. Z.
// Correct and efficient work-stealing for weak memory models
// Proceedings of the 18th ACM SIGPLAN symposium on Principles and
// practice of parallel programming (PPoPP 2013), 69-80
//
Z
zgu 已提交
284 285 286

template <class E, MEMFLAGS F, unsigned int N = TASKQUEUE_SIZE>
class GenericTaskQueue: public TaskQueueSuper<N, F> {
287
  ArrayAllocator<E, F> _array_allocator;
288
protected:
Z
zgu 已提交
289 290
  typedef typename TaskQueueSuper<N, F>::Age Age;
  typedef typename TaskQueueSuper<N, F>::idx_t idx_t;
291

Z
zgu 已提交
292 293 294 295 296
  using TaskQueueSuper<N, F>::_bottom;
  using TaskQueueSuper<N, F>::_age;
  using TaskQueueSuper<N, F>::increment_index;
  using TaskQueueSuper<N, F>::decrement_index;
  using TaskQueueSuper<N, F>::dirty_size;
297 298

public:
Z
zgu 已提交
299 300 301 302 303 304
  using TaskQueueSuper<N, F>::max_elems;
  using TaskQueueSuper<N, F>::size;

#if  TASKQUEUE_STATS
  using TaskQueueSuper<N, F>::stats;
#endif
305

D
duke 已提交
306 307
private:
  // Slow paths for push, pop_local.  (pop_global has no fast path.)
308 309
  bool push_slow(E t, uint dirty_n_elems);
  bool pop_local_slow(uint localBot, Age oldAge);
D
duke 已提交
310 311

public:
312 313
  typedef E element_type;

D
duke 已提交
314 315 316 317 318
  // Initializes the queue to empty.
  GenericTaskQueue();

  void initialize();

319
  // Push the task "t" on the queue.  Returns "false" iff the queue is full.
D
duke 已提交
320 321
  inline bool push(E t);

322 323 324
  // Attempts to claim a task from the "local" end of the queue (the most
  // recently pushed).  If successful, returns true and sets t to the task;
  // otherwise, returns false (the queue is empty).
D
duke 已提交
325 326
  inline bool pop_local(E& t);

327 328
  // Like pop_local(), but uses the "global" end of the queue (the least
  // recently pushed).
D
duke 已提交
329 330 331 332 333
  bool pop_global(E& t);

  // Delete any resource associated with the queue.
  ~GenericTaskQueue();

334 335 336
  // apply the closure to all elements in the task queue
  void oops_do(OopClosure* f);

D
duke 已提交
337 338 339 340 341
private:
  // Element array.
  volatile E* _elems;
};

Z
zgu 已提交
342 343
template<class E, MEMFLAGS F, unsigned int N>
GenericTaskQueue<E, F, N>::GenericTaskQueue() {
344
  assert(sizeof(Age) == sizeof(size_t), "Depends on this.");
D
duke 已提交
345 346
}

Z
zgu 已提交
347 348
template<class E, MEMFLAGS F, unsigned int N>
void GenericTaskQueue<E, F, N>::initialize() {
349
  _elems = _array_allocator.allocate(N);
D
duke 已提交
350 351
}

Z
zgu 已提交
352 353
template<class E, MEMFLAGS F, unsigned int N>
void GenericTaskQueue<E, F, N>::oops_do(OopClosure* f) {
354
  // tty->print_cr("START OopTaskQueue::oops_do");
355 356 357
  uint iters = size();
  uint index = _bottom;
  for (uint i = 0; i < iters; ++i) {
358 359 360 361 362 363 364 365 366 367 368
    index = decrement_index(index);
    // tty->print_cr("  doing entry %d," INTPTR_T " -> " INTPTR_T,
    //            index, &_elems[index], _elems[index]);
    E* t = (E*)&_elems[index];      // cast away volatility
    oop* p = (oop*)t;
    assert((*t)->is_oop_or_null(), "Not an oop or null");
    f->do_oop(p);
  }
  // tty->print_cr("END OopTaskQueue::oops_do");
}

Z
zgu 已提交
369 370
template<class E, MEMFLAGS F, unsigned int N>
bool GenericTaskQueue<E, F, N>::push_slow(E t, uint dirty_n_elems) {
371
  if (dirty_n_elems == N - 1) {
D
duke 已提交
372
    // Actually means 0, so do the push.
373
    uint localBot = _bottom;
374 375 376 377 378 379
    // g++ complains if the volatile result of the assignment is
    // unused, so we cast the volatile away.  We cannot cast directly
    // to void, because gcc treats that as not using the result of the
    // assignment.  However, casting to E& means that we trigger an
    // unused-value warning.  So, we cast the E& to void.
    (void)const_cast<E&>(_elems[localBot] = t);
380
    OrderAccess::release_store(&_bottom, increment_index(localBot));
J
jcoomes 已提交
381
    TASKQUEUE_STATS_ONLY(stats.record_push());
D
duke 已提交
382
    return true;
383 384
  }
  return false;
D
duke 已提交
385 386
}

387 388 389 390 391 392
// pop_local_slow() is done by the owning thread and is trying to
// get the last task in the queue.  It will compete with pop_global()
// that will be used by other threads.  The tag age is incremented
// whenever the queue goes empty which it will do here if this thread
// gets the last task or in pop_global() if the queue wraps (top == 0
// and pop_global() succeeds, see pop_global()).
Z
zgu 已提交
393 394
template<class E, MEMFLAGS F, unsigned int N>
bool GenericTaskQueue<E, F, N>::pop_local_slow(uint localBot, Age oldAge) {
D
duke 已提交
395 396 397 398 399 400 401 402 403
  // This queue was observed to contain exactly one element; either this
  // thread will claim it, or a competing "pop_global".  In either case,
  // the queue will be logically empty afterwards.  Create a new Age value
  // that represents the empty queue for the given value of "_bottom".  (We
  // must also increment "tag" because of the case where "bottom == 1",
  // "top == 0".  A pop_global could read the queue element in that case,
  // then have the owner thread do a pop followed by another push.  Without
  // the incrementing of "tag", the pop_global's CAS could succeed,
  // allowing it to believe it has claimed the stale element.)
404
  Age newAge((idx_t)localBot, oldAge.tag() + 1);
D
duke 已提交
405 406 407 408 409
  // Perhaps a competing pop_global has already incremented "top", in which
  // case it wins the element.
  if (localBot == oldAge.top()) {
    // No competing pop_global has yet incremented "top"; we'll try to
    // install new_age, thus claiming the element.
410
    Age tempAge = _age.cmpxchg(newAge, oldAge);
D
duke 已提交
411 412
    if (tempAge == oldAge) {
      // We win.
413
      assert(dirty_size(localBot, _age.top()) != N - 1, "sanity");
J
jcoomes 已提交
414
      TASKQUEUE_STATS_ONLY(stats.record_pop_slow());
D
duke 已提交
415 416 417
      return true;
    }
  }
418 419 420 421 422
  // We lose; a completing pop_global gets the element.  But the queue is empty
  // and top is greater than bottom.  Fix this representation of the empty queue
  // to become the canonical one.
  _age.set(newAge);
  assert(dirty_size(localBot, _age.top()) != N - 1, "sanity");
D
duke 已提交
423 424 425
  return false;
}

Z
zgu 已提交
426 427
template<class E, MEMFLAGS F, unsigned int N>
bool GenericTaskQueue<E, F, N>::pop_global(E& t) {
428
  Age oldAge = _age.get();
429 430 431 432 433 434 435
  // Architectures with weak memory model require a barrier here
  // to guarantee that bottom is not older than age,
  // which is crucial for the correctness of the algorithm.
#if !(defined SPARC || defined IA32 || defined AMD64)
  OrderAccess::fence();
#endif
  uint localBot = OrderAccess::load_acquire((volatile juint*)&_bottom);
436
  uint n_elems = size(localBot, oldAge.top());
D
duke 已提交
437 438 439
  if (n_elems == 0) {
    return false;
  }
440

441 442 443 444 445 446
  // g++ complains if the volatile result of the assignment is
  // unused, so we cast the volatile away.  We cannot cast directly
  // to void, because gcc treats that as not using the result of the
  // assignment.  However, casting to E& means that we trigger an
  // unused-value warning.  So, we cast the E& to void.
  (void) const_cast<E&>(t = _elems[oldAge.top()]);
447 448 449 450
  Age newAge(oldAge);
  newAge.increment();
  Age resAge = _age.cmpxchg(newAge, oldAge);

D
duke 已提交
451 452
  // Note that using "_bottom" here might fail, since a pop_local might
  // have decremented it.
453 454
  assert(dirty_size(localBot, newAge.top()) != N - 1, "sanity");
  return resAge == oldAge;
D
duke 已提交
455 456
}

Z
zgu 已提交
457 458 459
template<class E, MEMFLAGS F, unsigned int N>
GenericTaskQueue<E, F, N>::~GenericTaskQueue() {
  FREE_C_HEAP_ARRAY(E, _elems, F);
D
duke 已提交
460 461
}

462 463 464
// OverflowTaskQueue is a TaskQueue that also includes an overflow stack for
// elements that do not fit in the TaskQueue.
//
465
// This class hides two methods from super classes:
466 467 468 469
//
// push() - push onto the task queue or, if that fails, onto the overflow stack
// is_empty() - return true if both the TaskQueue and overflow stack are empty
//
470
// Note that size() is not hidden--it returns the number of elements in the
471 472
// TaskQueue, and does not include the size of the overflow stack.  This
// simplifies replacement of GenericTaskQueues with OverflowTaskQueues.
Z
zgu 已提交
473 474
template<class E, MEMFLAGS F, unsigned int N = TASKQUEUE_SIZE>
class OverflowTaskQueue: public GenericTaskQueue<E, F, N>
475 476
{
public:
Z
zgu 已提交
477 478
  typedef Stack<E, F>               overflow_t;
  typedef GenericTaskQueue<E, F, N> taskqueue_t;
479

J
jcoomes 已提交
480 481
  TASKQUEUE_STATS_ONLY(using taskqueue_t::stats;)

482 483 484 485 486 487
  // Push task t onto the queue or onto the overflow stack.  Return true.
  inline bool push(E t);

  // Attempt to pop from the overflow stack; return true if anything was popped.
  inline bool pop_overflow(E& t);

488 489
  inline overflow_t* overflow_stack() { return &_overflow_stack; }

490
  inline bool taskqueue_empty() const { return taskqueue_t::is_empty(); }
491
  inline bool overflow_empty()  const { return _overflow_stack.is_empty(); }
492 493 494 495 496
  inline bool is_empty()        const {
    return taskqueue_empty() && overflow_empty();
  }

private:
497
  overflow_t _overflow_stack;
498 499
};

Z
zgu 已提交
500 501
template <class E, MEMFLAGS F, unsigned int N>
bool OverflowTaskQueue<E, F, N>::push(E t)
502 503 504
{
  if (!taskqueue_t::push(t)) {
    overflow_stack()->push(t);
505
    TASKQUEUE_STATS_ONLY(stats.record_overflow(overflow_stack()->size()));
506 507 508 509
  }
  return true;
}

Z
zgu 已提交
510 511
template <class E, MEMFLAGS F, unsigned int N>
bool OverflowTaskQueue<E, F, N>::pop_overflow(E& t)
512 513 514 515 516 517
{
  if (overflow_empty()) return false;
  t = overflow_stack()->pop();
  return true;
}

Z
zgu 已提交
518
class TaskQueueSetSuper {
D
duke 已提交
519 520 521 522 523 524 525
protected:
  static int randomParkAndMiller(int* seed0);
public:
  // Returns "true" if some TaskQueue in the set contains a task.
  virtual bool peek() = 0;
};

Z
zgu 已提交
526 527 528 529 530
template <MEMFLAGS F> class TaskQueueSetSuperImpl: public CHeapObj<F>, public TaskQueueSetSuper {
};

template<class T, MEMFLAGS F>
class GenericTaskQueueSet: public TaskQueueSetSuperImpl<F> {
D
duke 已提交
531
private:
532
  uint _n;
533
  T** _queues;
D
duke 已提交
534 535

public:
536 537
  typedef typename T::element_type E;

D
duke 已提交
538
  GenericTaskQueueSet(int n) : _n(n) {
539
    typedef T* GenericTaskQueuePtr;
Z
zgu 已提交
540
    _queues = NEW_C_HEAP_ARRAY(GenericTaskQueuePtr, n, F);
D
duke 已提交
541 542 543 544 545
    for (int i = 0; i < n; i++) {
      _queues[i] = NULL;
    }
  }

546
  bool steal_best_of_2(uint queue_num, int* seed, E& t);
D
duke 已提交
547

548
  void register_queue(uint i, T* q);
D
duke 已提交
549

550
  T* queue(uint n);
D
duke 已提交
551

552 553 554 555 556
  // The thread with queue number "queue_num" (and whose random number seed is
  // at "seed") is trying to steal a task from some other queue.  (It may try
  // several queues, according to some configuration parameter.)  If some steal
  // succeeds, returns "true" and sets "t" to the stolen task, otherwise returns
  // false.
557
  bool steal(uint queue_num, int* seed, E& t);
D
duke 已提交
558 559 560 561

  bool peek();
};

Z
zgu 已提交
562 563
template<class T, MEMFLAGS F> void
GenericTaskQueueSet<T, F>::register_queue(uint i, T* q) {
564
  assert(i < _n, "index out of range.");
D
duke 已提交
565 566 567
  _queues[i] = q;
}

Z
zgu 已提交
568 569
template<class T, MEMFLAGS F> T*
GenericTaskQueueSet<T, F>::queue(uint i) {
D
duke 已提交
570 571 572
  return _queues[i];
}

Z
zgu 已提交
573 574
template<class T, MEMFLAGS F> bool
GenericTaskQueueSet<T, F>::steal(uint queue_num, int* seed, E& t) {
J
jcoomes 已提交
575 576 577
  for (uint i = 0; i < 2 * _n; i++) {
    if (steal_best_of_2(queue_num, seed, t)) {
      TASKQUEUE_STATS_ONLY(queue(queue_num)->stats.record_steal(true));
D
duke 已提交
578
      return true;
J
jcoomes 已提交
579 580 581
    }
  }
  TASKQUEUE_STATS_ONLY(queue(queue_num)->stats.record_steal(false));
D
duke 已提交
582 583 584
  return false;
}

Z
zgu 已提交
585 586
template<class T, MEMFLAGS F> bool
GenericTaskQueueSet<T, F>::steal_best_of_2(uint queue_num, int* seed, E& t) {
D
duke 已提交
587
  if (_n > 2) {
588
    uint k1 = queue_num;
Z
zgu 已提交
589
    while (k1 == queue_num) k1 = TaskQueueSetSuper::randomParkAndMiller(seed) % _n;
590
    uint k2 = queue_num;
Z
zgu 已提交
591
    while (k2 == queue_num || k2 == k1) k2 = TaskQueueSetSuper::randomParkAndMiller(seed) % _n;
D
duke 已提交
592
    // Sample both and try the larger.
593 594
    uint sz1 = _queues[k1]->size();
    uint sz2 = _queues[k2]->size();
D
duke 已提交
595 596 597 598
    if (sz2 > sz1) return _queues[k2]->pop_global(t);
    else return _queues[k1]->pop_global(t);
  } else if (_n == 2) {
    // Just try the other one.
599
    uint k = (queue_num + 1) % 2;
D
duke 已提交
600 601 602 603 604 605 606
    return _queues[k]->pop_global(t);
  } else {
    assert(_n == 1, "can't be zero.");
    return false;
  }
}

Z
zgu 已提交
607 608
template<class T, MEMFLAGS F>
bool GenericTaskQueueSet<T, F>::peek() {
D
duke 已提交
609
  // Try all the queues.
610
  for (uint j = 0; j < _n; j++) {
D
duke 已提交
611 612 613 614 615 616
    if (_queues[j]->peek())
      return true;
  }
  return false;
}

617
// When to terminate from the termination protocol.
Z
zgu 已提交
618
class TerminatorTerminator: public CHeapObj<mtInternal> {
619 620 621 622
public:
  virtual bool should_exit_termination() = 0;
};

D
duke 已提交
623 624 625
// A class to aid in the termination of a set of parallel tasks using
// TaskQueueSet's for work stealing.

626 627
#undef TRACESPINNING

D
duke 已提交
628 629 630 631
class ParallelTaskTerminator: public StackObj {
private:
  int _n_threads;
  TaskQueueSetSuper* _queue_set;
632
  int _offered_termination;
D
duke 已提交
633

634 635 636 637 638 639
#ifdef TRACESPINNING
  static uint _total_yields;
  static uint _total_spins;
  static uint _total_peeks;
#endif

D
duke 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
  bool peek_in_queue_set();
protected:
  virtual void yield();
  void sleep(uint millis);

public:

  // "n_threads" is the number of threads to be terminated.  "queue_set" is a
  // queue sets of work queues of other threads.
  ParallelTaskTerminator(int n_threads, TaskQueueSetSuper* queue_set);

  // The current thread has no work, and is ready to terminate if everyone
  // else is.  If returns "true", all threads are terminated.  If returns
  // "false", available work has been observed in one of the task queues,
  // so the global task is not complete.
655 656 657 658
  bool offer_termination() {
    return offer_termination(NULL);
  }

659
  // As above, but it also terminates if the should_exit_termination()
660 661 662
  // method of the terminator parameter returns true. If terminator is
  // NULL, then it is ignored.
  bool offer_termination(TerminatorTerminator* terminator);
D
duke 已提交
663 664 665 666 667 668

  // Reset the terminator, so that it may be reused again.
  // The caller is responsible for ensuring that this is done
  // in an MT-safe manner, once the previous round of use of
  // the terminator is finished.
  void reset_for_reuse();
669 670 671
  // Same as above but the number of parallel threads is set to the
  // given number.
  void reset_for_reuse(int n_threads);
D
duke 已提交
672

673 674 675 676 677 678
#ifdef TRACESPINNING
  static uint total_yields() { return _total_yields; }
  static uint total_spins() { return _total_spins; }
  static uint total_peeks() { return _total_peeks; }
  static void print_termination_counts();
#endif
D
duke 已提交
679 680
};

Z
zgu 已提交
681 682
template<class E, MEMFLAGS F, unsigned int N> inline bool
GenericTaskQueue<E, F, N>::push(E t) {
683
  uint localBot = _bottom;
684
  assert(localBot < N, "_bottom out of range.");
685
  idx_t top = _age.top();
686
  uint dirty_n_elems = dirty_size(localBot, top);
687
  assert(dirty_n_elems < N, "n_elems out of range.");
D
duke 已提交
688
  if (dirty_n_elems < max_elems()) {
689 690 691 692 693 694
    // g++ complains if the volatile result of the assignment is
    // unused, so we cast the volatile away.  We cannot cast directly
    // to void, because gcc treats that as not using the result of the
    // assignment.  However, casting to E& means that we trigger an
    // unused-value warning.  So, we cast the E& to void.
    (void) const_cast<E&>(_elems[localBot] = t);
695
    OrderAccess::release_store(&_bottom, increment_index(localBot));
J
jcoomes 已提交
696
    TASKQUEUE_STATS_ONLY(stats.record_push());
D
duke 已提交
697 698 699 700 701 702
    return true;
  } else {
    return push_slow(t, dirty_n_elems);
  }
}

Z
zgu 已提交
703 704
template<class E, MEMFLAGS F, unsigned int N> inline bool
GenericTaskQueue<E, F, N>::pop_local(E& t) {
705
  uint localBot = _bottom;
706
  // This value cannot be N-1.  That can only occur as a result of
D
duke 已提交
707
  // the assignment to bottom in this method.  If it does, this method
708
  // resets the size to 0 before the next call (which is sequential,
D
duke 已提交
709
  // since this is pop_local.)
710 711
  uint dirty_n_elems = dirty_size(localBot, _age.top());
  assert(dirty_n_elems != N - 1, "Shouldn't be possible...");
D
duke 已提交
712 713 714 715 716 717
  if (dirty_n_elems == 0) return false;
  localBot = decrement_index(localBot);
  _bottom = localBot;
  // This is necessary to prevent any read below from being reordered
  // before the store just above.
  OrderAccess::fence();
718 719 720 721 722 723
  // g++ complains if the volatile result of the assignment is
  // unused, so we cast the volatile away.  We cannot cast directly
  // to void, because gcc treats that as not using the result of the
  // assignment.  However, casting to E& means that we trigger an
  // unused-value warning.  So, we cast the E& to void.
  (void) const_cast<E&>(t = _elems[localBot]);
D
duke 已提交
724 725 726 727
  // This is a second read of "age"; the "size()" above is the first.
  // If there's still at least one element in the queue, based on the
  // "_bottom" and "age" we've read, then there can be no interference with
  // a "pop_global" operation, and we're done.
728
  idx_t tp = _age.top();    // XXX
D
duke 已提交
729
  if (size(localBot, tp) > 0) {
730
    assert(dirty_size(localBot, tp) != N - 1, "sanity");
J
jcoomes 已提交
731
    TASKQUEUE_STATS_ONLY(stats.record_pop());
D
duke 已提交
732 733 734 735
    return true;
  } else {
    // Otherwise, the queue contained exactly one element; we take the slow
    // path.
736
    return pop_local_slow(localBot, _age.get());
D
duke 已提交
737 738 739
  }
}

Z
zgu 已提交
740 741
typedef GenericTaskQueue<oop, mtGC>             OopTaskQueue;
typedef GenericTaskQueueSet<OopTaskQueue, mtGC> OopTaskQueueSet;
D
duke 已提交
742

743 744 745 746 747
#ifdef _MSC_VER
#pragma warning(push)
// warning C4522: multiple assignment operators specified
#pragma warning(disable:4522)
#endif
748 749 750 751 752 753

// This is a container class for either an oop* or a narrowOop*.
// Both are pushed onto a task queue and the consumer will test is_narrow()
// to determine which should be processed.
class StarTask {
  void*  _holder;        // either union oop* or narrowOop*
754 755 756

  enum { COMPRESSED_OOP_MASK = 1 };

757
 public:
758 759 760 761 762 763 764 765
  StarTask(narrowOop* p) {
    assert(((uintptr_t)p & COMPRESSED_OOP_MASK) == 0, "Information loss!");
    _holder = (void *)((uintptr_t)p | COMPRESSED_OOP_MASK);
  }
  StarTask(oop* p)       {
    assert(((uintptr_t)p & COMPRESSED_OOP_MASK) == 0, "Information loss!");
    _holder = (void*)p;
  }
766 767 768 769 770 771
  StarTask()             { _holder = NULL; }
  operator oop*()        { return (oop*)_holder; }
  operator narrowOop*()  {
    return (narrowOop*)((uintptr_t)_holder & ~COMPRESSED_OOP_MASK);
  }

772 773 774 775 776 777 778 779
  StarTask& operator=(const StarTask& t) {
    _holder = t._holder;
    return *this;
  }
  volatile StarTask& operator=(const volatile StarTask& t) volatile {
    _holder = t._holder;
    return *this;
  }
780 781 782 783 784 785

  bool is_narrow() const {
    return (((uintptr_t)_holder & COMPRESSED_OOP_MASK) != 0);
  }
};

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
class ObjArrayTask
{
public:
  ObjArrayTask(oop o = NULL, int idx = 0): _obj(o), _index(idx) { }
  ObjArrayTask(oop o, size_t idx): _obj(o), _index(int(idx)) {
    assert(idx <= size_t(max_jint), "too big");
  }
  ObjArrayTask(const ObjArrayTask& t): _obj(t._obj), _index(t._index) { }

  ObjArrayTask& operator =(const ObjArrayTask& t) {
    _obj = t._obj;
    _index = t._index;
    return *this;
  }
  volatile ObjArrayTask&
  operator =(const volatile ObjArrayTask& t) volatile {
    _obj = t._obj;
    _index = t._index;
    return *this;
  }

  inline oop obj()   const { return _obj; }
  inline int index() const { return _index; }

  DEBUG_ONLY(bool is_valid() const); // Tasks to be pushed/popped must be valid.

private:
  oop _obj;
  int _index;
};

#ifdef _MSC_VER
#pragma warning(pop)
#endif

Z
zgu 已提交
821 822
typedef OverflowTaskQueue<StarTask, mtClass>           OopStarTaskQueue;
typedef GenericTaskQueueSet<OopStarTaskQueue, mtClass> OopStarTaskQueueSet;
D
duke 已提交
823

Z
zgu 已提交
824 825
typedef OverflowTaskQueue<size_t, mtInternal>             RegionTaskQueue;
typedef GenericTaskQueueSet<RegionTaskQueue, mtClass>     RegionTaskQueueSet;
826

827 828

#endif // SHARE_VM_UTILITIES_TASKQUEUE_HPP