taskqueue.hpp revision 1472
7321N/A/*
7321N/A * Copyright (c) 2001, 2009, Oracle and/or its affiliates. All rights reserved.
7321N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7321N/A *
7321N/A * This code is free software; you can redistribute it and/or modify it
7321N/A * under the terms of the GNU General Public License version 2 only, as
7321N/A * published by the Free Software Foundation.
7321N/A *
7321N/A * This code is distributed in the hope that it will be useful, but WITHOUT
7321N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
7321N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
7321N/A * version 2 for more details (a copy is included in the LICENSE file that
7321N/A * accompanied this code).
7321N/A *
7321N/A * You should have received a copy of the GNU General Public License version
7321N/A * 2 along with this work; if not, write to the Free Software Foundation,
7321N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
7321N/A *
7321N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
7321N/A * or visit www.oracle.com if you need additional information or have any
7321N/A * questions.
7321N/A *
7321N/A */
7321N/A
7321N/Atemplate <unsigned int N>
7321N/Aclass TaskQueueSuper: public CHeapObj {
7321N/Aprotected:
7321N/A // Internal type for indexing the queue; also used for the tag.
7321N/A typedef NOT_LP64(uint16_t) LP64_ONLY(uint32_t) idx_t;
7321N/A
7321N/A // The first free element after the last one pushed (mod N).
7321N/A volatile uint _bottom;
7321N/A
7321N/A enum { MOD_N_MASK = N - 1 };
7321N/A
7321N/A class Age {
7321N/A public:
7321N/A Age(size_t data = 0) { _data = data; }
7321N/A Age(const Age& age) { _data = age._data; }
7321N/A Age(idx_t top, idx_t tag) { _fields._top = top; _fields._tag = tag; }
7321N/A
7321N/A Age get() const volatile { return _data; }
7321N/A void set(Age age) volatile { _data = age._data; }
7321N/A
7321N/A idx_t top() const volatile { return _fields._top; }
7321N/A idx_t tag() const volatile { return _fields._tag; }
7321N/A
7321N/A // Increment top; if it wraps, increment tag also.
7321N/A void increment() {
7321N/A _fields._top = increment_index(_fields._top);
7321N/A if (_fields._top == 0) ++_fields._tag;
7321N/A }
7321N/A
7321N/A Age cmpxchg(const Age new_age, const Age old_age) volatile {
7321N/A return (size_t) Atomic::cmpxchg_ptr((intptr_t)new_age._data,
7321N/A (volatile intptr_t *)&_data,
7321N/A (intptr_t)old_age._data);
7321N/A }
7321N/A
7321N/A bool operator ==(const Age& other) const { return _data == other._data; }
7321N/A
7321N/A private:
7321N/A struct fields {
7321N/A idx_t _top;
7321N/A idx_t _tag;
7321N/A };
7321N/A union {
7321N/A size_t _data;
7321N/A fields _fields;
7321N/A };
7321N/A };
7321N/A
7321N/A volatile Age _age;
7321N/A
7321N/A // These both operate mod N.
7321N/A static uint increment_index(uint ind) {
7321N/A return (ind + 1) & MOD_N_MASK;
7321N/A }
7321N/A static uint decrement_index(uint ind) {
7321N/A return (ind - 1) & MOD_N_MASK;
7321N/A }
7321N/A
7321N/A // Returns a number in the range [0..N). If the result is "N-1", it should be
7321N/A // interpreted as 0.
7321N/A uint dirty_size(uint bot, uint top) const {
7321N/A return (bot - top) & MOD_N_MASK;
7321N/A }
7321N/A
7321N/A // Returns the size corresponding to the given "bot" and "top".
7321N/A uint size(uint bot, uint top) const {
7321N/A uint sz = dirty_size(bot, top);
7321N/A // Has the queue "wrapped", so that bottom is less than top? There's a
7321N/A // complicated special case here. A pair of threads could perform pop_local
7321N/A // and pop_global operations concurrently, starting from a state in which
7321N/A // _bottom == _top+1. The pop_local could succeed in decrementing _bottom,
7321N/A // and the pop_global in incrementing _top (in which case the pop_global
7321N/A // will be awarded the contested queue element.) The resulting state must
7321N/A // be interpreted as an empty queue. (We only need to worry about one such
7321N/A // event: only the queue owner performs pop_local's, and several concurrent
7321N/A // threads attempting to perform the pop_global will all perform the same
7321N/A // CAS, and only one can succeed.) Any stealing thread that reads after
7321N/A // either the increment or decrement will see an empty queue, and will not
7321N/A // join the competitors. The "sz == -1 || sz == N-1" state will not be
7321N/A // modified by concurrent queues, so the owner thread can reset the state to
7321N/A // _bottom == top so subsequent pushes will be performed normally.
7321N/A return (sz == N - 1) ? 0 : sz;
7321N/A }
7321N/A
7321N/Apublic:
7321N/A TaskQueueSuper() : _bottom(0), _age() {}
7321N/A
7321N/A // Return true if the TaskQueue contains any tasks.
7321N/A bool peek() { return _bottom != _age.top(); }
7321N/A
7321N/A // Return an estimate of the number of elements in the queue.
7321N/A // The "careful" version admits the possibility of pop_local/pop_global
7321N/A // races.
7321N/A uint size() const {
7321N/A return size(_bottom, _age.top());
7321N/A }
7321N/A
7321N/A uint dirty_size() const {
7321N/A return dirty_size(_bottom, _age.top());
7321N/A }
7321N/A
7321N/A void set_empty() {
7321N/A _bottom = 0;
7321N/A _age.set(0);
7321N/A }
7321N/A
7321N/A // Maximum number of elements allowed in the queue. This is two less
7321N/A // than the actual queue size, for somewhat complicated reasons.
7321N/A uint max_elems() const { return N - 2; }
7321N/A
7321N/A // Total size of queue.
7321N/A static const uint total_size() { return N; }
7321N/A};
7321N/A
7321N/Atemplate<class E, unsigned int N = TASKQUEUE_SIZE>
7321N/Aclass GenericTaskQueue: public TaskQueueSuper<N> {
7321N/Aprotected:
7321N/A typedef typename TaskQueueSuper<N>::Age Age;
7321N/A typedef typename TaskQueueSuper<N>::idx_t idx_t;
7321N/A
7321N/A using TaskQueueSuper<N>::_bottom;
7321N/A using TaskQueueSuper<N>::_age;
7321N/A using TaskQueueSuper<N>::increment_index;
7321N/A using TaskQueueSuper<N>::decrement_index;
7321N/A using TaskQueueSuper<N>::dirty_size;
7321N/A
7321N/Apublic:
7321N/A using TaskQueueSuper<N>::max_elems;
7321N/A using TaskQueueSuper<N>::size;
7321N/A
7321N/Aprivate:
7321N/A // Slow paths for push, pop_local. (pop_global has no fast path.)
7321N/A bool push_slow(E t, uint dirty_n_elems);
7321N/A bool pop_local_slow(uint localBot, Age oldAge);
7321N/A
7321N/Apublic:
7321N/A typedef E element_type;
7321N/A
7321N/A // Initializes the queue to empty.
7321N/A GenericTaskQueue();
7321N/A
7321N/A void initialize();
7321N/A
7321N/A // Push the task "t" on the queue. Returns "false" iff the queue is
7321N/A // full.
7321N/A inline bool push(E t);
7321N/A
7321N/A // If succeeds in claiming a task (from the 'local' end, that is, the
7321N/A // most recently pushed task), returns "true" and sets "t" to that task.
7321N/A // Otherwise, the queue is empty and returns false.
7321N/A inline bool pop_local(E& t);
7321N/A
7321N/A // If succeeds in claiming a task (from the 'global' end, that is, the
7321N/A // least recently pushed task), returns "true" and sets "t" to that task.
7321N/A // Otherwise, the queue is empty and returns false.
7321N/A bool pop_global(E& t);
7321N/A
7321N/A // Delete any resource associated with the queue.
7321N/A ~GenericTaskQueue();
7321N/A
7321N/A // apply the closure to all elements in the task queue
7321N/A void oops_do(OopClosure* f);
7321N/A
7321N/Aprivate:
7321N/A // Element array.
7321N/A volatile E* _elems;
7321N/A};
7321N/A
7321N/Atemplate<class E, unsigned int N>
7321N/AGenericTaskQueue<E, N>::GenericTaskQueue() {
7321N/A assert(sizeof(Age) == sizeof(size_t), "Depends on this.");
7321N/A}
7321N/A
7321N/Atemplate<class E, unsigned int N>
7321N/Avoid GenericTaskQueue<E, N>::initialize() {
7321N/A _elems = NEW_C_HEAP_ARRAY(E, N);
7321N/A guarantee(_elems != NULL, "Allocation failed.");
7321N/A}
7321N/A
7321N/Atemplate<class E, unsigned int N>
7321N/Avoid GenericTaskQueue<E, N>::oops_do(OopClosure* f) {
7321N/A // tty->print_cr("START OopTaskQueue::oops_do");
7321N/A uint iters = size();
7321N/A uint index = _bottom;
7321N/A for (uint i = 0; i < iters; ++i) {
7321N/A index = decrement_index(index);
7321N/A // tty->print_cr(" doing entry %d," INTPTR_T " -> " INTPTR_T,
7321N/A // index, &_elems[index], _elems[index]);
7321N/A E* t = (E*)&_elems[index]; // cast away volatility
7321N/A oop* p = (oop*)t;
7321N/A assert((*t)->is_oop_or_null(), "Not an oop or null");
7321N/A f->do_oop(p);
7321N/A }
7321N/A // tty->print_cr("END OopTaskQueue::oops_do");
7321N/A}
7321N/A
7321N/Atemplate<class E, unsigned int N>
7321N/Abool GenericTaskQueue<E, N>::push_slow(E t, uint dirty_n_elems) {
7321N/A if (dirty_n_elems == N - 1) {
7321N/A // Actually means 0, so do the push.
7321N/A uint localBot = _bottom;
7321N/A // g++ complains if the volatile result of the assignment is unused.
7321N/A const_cast<E&>(_elems[localBot] = t);
7321N/A OrderAccess::release_store(&_bottom, increment_index(localBot));
7321N/A return true;
7321N/A }
7321N/A return false;
7321N/A}
7321N/A
7321N/Atemplate<class E, unsigned int N>
7321N/Abool GenericTaskQueue<E, N>::
7321N/Apop_local_slow(uint localBot, Age oldAge) {
7321N/A // This queue was observed to contain exactly one element; either this
7321N/A // thread will claim it, or a competing "pop_global". In either case,
7321N/A // the queue will be logically empty afterwards. Create a new Age value
7321N/A // that represents the empty queue for the given value of "_bottom". (We
7321N/A // must also increment "tag" because of the case where "bottom == 1",
7321N/A // "top == 0". A pop_global could read the queue element in that case,
7321N/A // then have the owner thread do a pop followed by another push. Without
7321N/A // the incrementing of "tag", the pop_global's CAS could succeed,
7321N/A // allowing it to believe it has claimed the stale element.)
7321N/A Age newAge((idx_t)localBot, oldAge.tag() + 1);
7321N/A // Perhaps a competing pop_global has already incremented "top", in which
7321N/A // case it wins the element.
7321N/A if (localBot == oldAge.top()) {
7321N/A // No competing pop_global has yet incremented "top"; we'll try to
7321N/A // install new_age, thus claiming the element.
7321N/A Age tempAge = _age.cmpxchg(newAge, oldAge);
7321N/A if (tempAge == oldAge) {
7321N/A // We win.
7321N/A assert(dirty_size(localBot, _age.top()) != N - 1, "sanity");
7321N/A return true;
7321N/A }
7321N/A }
7321N/A // We lose; a completing pop_global gets the element. But the queue is empty
7321N/A // and top is greater than bottom. Fix this representation of the empty queue
7321N/A // to become the canonical one.
7321N/A _age.set(newAge);
7321N/A assert(dirty_size(localBot, _age.top()) != N - 1, "sanity");
7321N/A return false;
7321N/A}
7321N/A
7321N/Atemplate<class E, unsigned int N>
7321N/Abool GenericTaskQueue<E, N>::pop_global(E& t) {
7321N/A Age oldAge = _age.get();
7321N/A uint localBot = _bottom;
7321N/A uint n_elems = size(localBot, oldAge.top());
7321N/A if (n_elems == 0) {
7321N/A return false;
7321N/A }
7321N/A
7321N/A const_cast<E&>(t = _elems[oldAge.top()]);
7321N/A Age newAge(oldAge);
7321N/A newAge.increment();
7321N/A Age resAge = _age.cmpxchg(newAge, oldAge);
7321N/A
7321N/A // Note that using "_bottom" here might fail, since a pop_local might
7321N/A // have decremented it.
7321N/A assert(dirty_size(localBot, newAge.top()) != N - 1, "sanity");
7321N/A return resAge == oldAge;
7321N/A}
7321N/A
7321N/Atemplate<class E, unsigned int N>
7321N/AGenericTaskQueue<E, N>::~GenericTaskQueue() {
7321N/A FREE_C_HEAP_ARRAY(E, _elems);
7321N/A}
7321N/A
7321N/A// Inherits the typedef of "Task" from above.
7321N/Aclass TaskQueueSetSuper: public CHeapObj {
7321N/Aprotected:
7321N/A static int randomParkAndMiller(int* seed0);
7321N/Apublic:
7321N/A // Returns "true" if some TaskQueue in the set contains a task.
7321N/A virtual bool peek() = 0;
7321N/A};
7321N/A
7321N/Atemplate<class T>
7321N/Aclass GenericTaskQueueSet: public TaskQueueSetSuper {
7321N/Aprivate:
7321N/A uint _n;
7321N/A T** _queues;
7321N/A
public:
typedef typename T::element_type E;
GenericTaskQueueSet(int n) : _n(n) {
typedef T* GenericTaskQueuePtr;
_queues = NEW_C_HEAP_ARRAY(GenericTaskQueuePtr, n);
for (int i = 0; i < n; i++) {
_queues[i] = NULL;
}
}
bool steal_1_random(uint queue_num, int* seed, E& t);
bool steal_best_of_2(uint queue_num, int* seed, E& t);
bool steal_best_of_all(uint queue_num, int* seed, E& t);
void register_queue(uint i, T* q);
T* queue(uint n);
// 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" the stolen task,
// otherwise returns false.
bool steal(uint queue_num, int* seed, E& t);
bool peek();
};
template<class T> void
GenericTaskQueueSet<T>::register_queue(uint i, T* q) {
assert(i < _n, "index out of range.");
_queues[i] = q;
}
template<class T> T*
GenericTaskQueueSet<T>::queue(uint i) {
return _queues[i];
}
template<class T> bool
GenericTaskQueueSet<T>::steal(uint queue_num, int* seed, E& t) {
for (uint i = 0; i < 2 * _n; i++)
if (steal_best_of_2(queue_num, seed, t))
return true;
return false;
}
template<class T> bool
GenericTaskQueueSet<T>::steal_best_of_all(uint queue_num, int* seed, E& t) {
if (_n > 2) {
int best_k;
uint best_sz = 0;
for (uint k = 0; k < _n; k++) {
if (k == queue_num) continue;
uint sz = _queues[k]->size();
if (sz > best_sz) {
best_sz = sz;
best_k = k;
}
}
return best_sz > 0 && _queues[best_k]->pop_global(t);
} else if (_n == 2) {
// Just try the other one.
int k = (queue_num + 1) % 2;
return _queues[k]->pop_global(t);
} else {
assert(_n == 1, "can't be zero.");
return false;
}
}
template<class T> bool
GenericTaskQueueSet<T>::steal_1_random(uint queue_num, int* seed, E& t) {
if (_n > 2) {
uint k = queue_num;
while (k == queue_num) k = randomParkAndMiller(seed) % _n;
return _queues[2]->pop_global(t);
} else if (_n == 2) {
// Just try the other one.
int k = (queue_num + 1) % 2;
return _queues[k]->pop_global(t);
} else {
assert(_n == 1, "can't be zero.");
return false;
}
}
template<class T> bool
GenericTaskQueueSet<T>::steal_best_of_2(uint queue_num, int* seed, E& t) {
if (_n > 2) {
uint k1 = queue_num;
while (k1 == queue_num) k1 = randomParkAndMiller(seed) % _n;
uint k2 = queue_num;
while (k2 == queue_num || k2 == k1) k2 = randomParkAndMiller(seed) % _n;
// Sample both and try the larger.
uint sz1 = _queues[k1]->size();
uint sz2 = _queues[k2]->size();
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.
uint k = (queue_num + 1) % 2;
return _queues[k]->pop_global(t);
} else {
assert(_n == 1, "can't be zero.");
return false;
}
}
template<class T>
bool GenericTaskQueueSet<T>::peek() {
// Try all the queues.
for (uint j = 0; j < _n; j++) {
if (_queues[j]->peek())
return true;
}
return false;
}
// When to terminate from the termination protocol.
class TerminatorTerminator: public CHeapObj {
public:
virtual bool should_exit_termination() = 0;
};
// A class to aid in the termination of a set of parallel tasks using
// TaskQueueSet's for work stealing.
#undef TRACESPINNING
class ParallelTaskTerminator: public StackObj {
private:
int _n_threads;
TaskQueueSetSuper* _queue_set;
int _offered_termination;
#ifdef TRACESPINNING
static uint _total_yields;
static uint _total_spins;
static uint _total_peeks;
#endif
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.
bool offer_termination() {
return offer_termination(NULL);
}
// As above, but it also terminates if the should_exit_termination()
// method of the terminator parameter returns true. If terminator is
// NULL, then it is ignored.
bool offer_termination(TerminatorTerminator* terminator);
// 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();
#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
};
template<class E, unsigned int N> inline bool
GenericTaskQueue<E, N>::push(E t) {
uint localBot = _bottom;
assert((localBot >= 0) && (localBot < N), "_bottom out of range.");
idx_t top = _age.top();
uint dirty_n_elems = dirty_size(localBot, top);
assert(dirty_n_elems < N, "n_elems out of range.");
if (dirty_n_elems < max_elems()) {
// g++ complains if the volatile result of the assignment is unused.
const_cast<E&>(_elems[localBot] = t);
OrderAccess::release_store(&_bottom, increment_index(localBot));
return true;
} else {
return push_slow(t, dirty_n_elems);
}
}
template<class E, unsigned int N> inline bool
GenericTaskQueue<E, N>::pop_local(E& t) {
uint localBot = _bottom;
// This value cannot be N-1. That can only occur as a result of
// the assignment to bottom in this method. If it does, this method
// resets the size( to 0 before the next call (which is sequential,
// since this is pop_local.)
uint dirty_n_elems = dirty_size(localBot, _age.top());
assert(dirty_n_elems != N - 1, "Shouldn't be possible...");
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();
const_cast<E&>(t = _elems[localBot]);
// 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.
idx_t tp = _age.top(); // XXX
if (size(localBot, tp) > 0) {
assert(dirty_size(localBot, tp) != N - 1, "sanity");
return true;
} else {
// Otherwise, the queue contained exactly one element; we take the slow
// path.
return pop_local_slow(localBot, _age.get());
}
}
typedef oop Task;
typedef GenericTaskQueue<Task> OopTaskQueue;
typedef GenericTaskQueueSet<OopTaskQueue> OopTaskQueueSet;
#ifdef _MSC_VER
#pragma warning(push)
// warning C4522: multiple assignment operators specified
#pragma warning(disable:4522)
#endif
// 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*
enum { COMPRESSED_OOP_MASK = 1 };
public:
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;
}
StarTask() { _holder = NULL; }
operator oop*() { return (oop*)_holder; }
operator narrowOop*() {
return (narrowOop*)((uintptr_t)_holder & ~COMPRESSED_OOP_MASK);
}
StarTask& operator=(const StarTask& t) {
_holder = t._holder;
return *this;
}
volatile StarTask& operator=(const volatile StarTask& t) volatile {
_holder = t._holder;
return *this;
}
bool is_narrow() const {
return (((uintptr_t)_holder & COMPRESSED_OOP_MASK) != 0);
}
};
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
typedef GenericTaskQueue<StarTask> OopStarTaskQueue;
typedef GenericTaskQueueSet<OopStarTaskQueue> OopStarTaskQueueSet;
typedef size_t RegionTask; // index for region
typedef GenericTaskQueue<RegionTask> RegionTaskQueue;
typedef GenericTaskQueueSet<RegionTaskQueue> RegionTaskQueueSet;
class RegionTaskQueueWithOverflow: public CHeapObj {
protected:
RegionTaskQueue _region_queue;
GrowableArray<RegionTask>* _overflow_stack;
public:
RegionTaskQueueWithOverflow() : _overflow_stack(NULL) {}
// Initialize both stealable queue and overflow
void initialize();
// Save first to stealable queue and then to overflow
void save(RegionTask t);
// Retrieve first from overflow and then from stealable queue
bool retrieve(RegionTask& region_index);
// Retrieve from stealable queue
bool retrieve_from_stealable_queue(RegionTask& region_index);
// Retrieve from overflow
bool retrieve_from_overflow(RegionTask& region_index);
bool is_empty();
bool stealable_is_empty();
bool overflow_is_empty();
uint stealable_size() { return _region_queue.size(); }
RegionTaskQueue* task_queue() { return &_region_queue; }
};
#define USE_RegionTaskQueueWithOverflow