taskqueue.hpp revision 113
0N/A/*
0N/A * Copyright 2001-2006 Sun Microsystems, Inc. All Rights Reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
0N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0N/A * CA 95054 USA or visit www.sun.com if you need additional information or
0N/A * have any questions.
0N/A *
0N/A */
0N/A
0N/Aclass TaskQueueSuper: public CHeapObj {
0N/Aprotected:
0N/A // The first free element after the last one pushed (mod _n).
0N/A // (For now we'll assume only 32-bit CAS).
0N/A volatile juint _bottom;
0N/A
0N/A // log2 of the size of the queue.
0N/A enum SomeProtectedConstants {
0N/A Log_n = 14
0N/A };
0N/A
0N/A // Size of the queue.
0N/A juint n() { return (1 << Log_n); }
0N/A // For computing "x mod n" efficiently.
0N/A juint n_mod_mask() { return n() - 1; }
0N/A
0N/A struct Age {
0N/A jushort _top;
0N/A jushort _tag;
0N/A
0N/A jushort tag() const { return _tag; }
0N/A jushort top() const { return _top; }
0N/A
0N/A Age() { _tag = 0; _top = 0; }
0N/A
0N/A friend bool operator ==(const Age& a1, const Age& a2) {
0N/A return a1.tag() == a2.tag() && a1.top() == a2.top();
0N/A }
0N/A
0N/A };
0N/A Age _age;
0N/A // These make sure we do single atomic reads and writes.
0N/A Age get_age() {
0N/A jint res = *(volatile jint*)(&_age);
0N/A return *(Age*)(&res);
0N/A }
0N/A void set_age(Age a) {
0N/A *(volatile jint*)(&_age) = *(int*)(&a);
0N/A }
0N/A
0N/A jushort get_top() {
0N/A return get_age().top();
0N/A }
0N/A
0N/A // These both operate mod _n.
0N/A juint increment_index(juint ind) {
0N/A return (ind + 1) & n_mod_mask();
0N/A }
0N/A juint decrement_index(juint ind) {
0N/A return (ind - 1) & n_mod_mask();
0N/A }
0N/A
0N/A // Returns a number in the range [0.._n). If the result is "n-1", it
0N/A // should be interpreted as 0.
0N/A juint dirty_size(juint bot, juint top) {
0N/A return ((jint)bot - (jint)top) & n_mod_mask();
0N/A }
0N/A
0N/A // Returns the size corresponding to the given "bot" and "top".
0N/A juint size(juint bot, juint top) {
0N/A juint sz = dirty_size(bot, top);
0N/A // Has the queue "wrapped", so that bottom is less than top?
0N/A // There's a complicated special case here. A pair of threads could
0N/A // perform pop_local and pop_global operations concurrently, starting
0N/A // from a state in which _bottom == _top+1. The pop_local could
0N/A // succeed in decrementing _bottom, and the pop_global in incrementing
0N/A // _top (in which case the pop_global will be awarded the contested
0N/A // queue element.) The resulting state must be interpreted as an empty
0N/A // queue. (We only need to worry about one such event: only the queue
0N/A // owner performs pop_local's, and several concurrent threads
0N/A // attempting to perform the pop_global will all perform the same CAS,
0N/A // and only one can succeed. Any stealing thread that reads after
0N/A // either the increment or decrement will seen an empty queue, and will
0N/A // not join the competitors. The "sz == -1 || sz == _n-1" state will
0N/A // not be modified by concurrent queues, so the owner thread can reset
0N/A // the state to _bottom == top so subsequent pushes will be performed
0N/A // normally.
0N/A if (sz == (n()-1)) return 0;
0N/A else return sz;
0N/A }
0N/A
0N/Apublic:
0N/A TaskQueueSuper() : _bottom(0), _age() {}
0N/A
0N/A // Return "true" if the TaskQueue contains any tasks.
0N/A bool peek();
0N/A
0N/A // Return an estimate of the number of elements in the queue.
0N/A // The "careful" version admits the possibility of pop_local/pop_global
0N/A // races.
0N/A juint size() {
0N/A return size(_bottom, get_top());
0N/A }
0N/A
0N/A juint dirty_size() {
0N/A return dirty_size(_bottom, get_top());
0N/A }
0N/A
0N/A // Maximum number of elements allowed in the queue. This is two less
0N/A // than the actual queue size, for somewhat complicated reasons.
0N/A juint max_elems() { return n() - 2; }
0N/A
0N/A};
0N/A
0N/Atemplate<class E> class GenericTaskQueue: public TaskQueueSuper {
0N/Aprivate:
0N/A // Slow paths for push, pop_local. (pop_global has no fast path.)
0N/A bool push_slow(E t, juint dirty_n_elems);
0N/A bool pop_local_slow(juint localBot, Age oldAge);
0N/A
0N/Apublic:
0N/A // Initializes the queue to empty.
0N/A GenericTaskQueue();
0N/A
0N/A void initialize();
0N/A
0N/A // Push the task "t" on the queue. Returns "false" iff the queue is
0N/A // full.
0N/A inline bool push(E t);
0N/A
0N/A // If succeeds in claiming a task (from the 'local' end, that is, the
0N/A // most recently pushed task), returns "true" and sets "t" to that task.
0N/A // Otherwise, the queue is empty and returns false.
0N/A inline bool pop_local(E& t);
0N/A
0N/A // If succeeds in claiming a task (from the 'global' end, that is, the
0N/A // least recently pushed task), returns "true" and sets "t" to that task.
0N/A // Otherwise, the queue is empty and returns false.
0N/A bool pop_global(E& t);
0N/A
0N/A // Delete any resource associated with the queue.
0N/A ~GenericTaskQueue();
0N/A
0N/Aprivate:
0N/A // Element array.
0N/A volatile E* _elems;
0N/A};
0N/A
0N/Atemplate<class E>
0N/AGenericTaskQueue<E>::GenericTaskQueue():TaskQueueSuper() {
0N/A assert(sizeof(Age) == sizeof(jint), "Depends on this.");
0N/A}
0N/A
0N/Atemplate<class E>
0N/Avoid GenericTaskQueue<E>::initialize() {
0N/A _elems = NEW_C_HEAP_ARRAY(E, n());
0N/A guarantee(_elems != NULL, "Allocation failed.");
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueue<E>::push_slow(E t, juint dirty_n_elems) {
0N/A if (dirty_n_elems == n() - 1) {
0N/A // Actually means 0, so do the push.
0N/A juint localBot = _bottom;
0N/A _elems[localBot] = t;
0N/A _bottom = increment_index(localBot);
0N/A return true;
0N/A } else
0N/A return false;
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueue<E>::
0N/Apop_local_slow(juint localBot, Age oldAge) {
0N/A // This queue was observed to contain exactly one element; either this
0N/A // thread will claim it, or a competing "pop_global". In either case,
0N/A // the queue will be logically empty afterwards. Create a new Age value
0N/A // that represents the empty queue for the given value of "_bottom". (We
0N/A // must also increment "tag" because of the case where "bottom == 1",
0N/A // "top == 0". A pop_global could read the queue element in that case,
0N/A // then have the owner thread do a pop followed by another push. Without
0N/A // the incrementing of "tag", the pop_global's CAS could succeed,
0N/A // allowing it to believe it has claimed the stale element.)
0N/A Age newAge;
0N/A newAge._top = localBot;
0N/A newAge._tag = oldAge.tag() + 1;
0N/A // Perhaps a competing pop_global has already incremented "top", in which
0N/A // case it wins the element.
0N/A if (localBot == oldAge.top()) {
0N/A Age tempAge;
0N/A // No competing pop_global has yet incremented "top"; we'll try to
0N/A // install new_age, thus claiming the element.
0N/A assert(sizeof(Age) == sizeof(jint) && sizeof(jint) == sizeof(juint),
0N/A "Assumption about CAS unit.");
0N/A *(jint*)&tempAge = Atomic::cmpxchg(*(jint*)&newAge, (volatile jint*)&_age, *(jint*)&oldAge);
0N/A if (tempAge == oldAge) {
0N/A // We win.
0N/A assert(dirty_size(localBot, get_top()) != n() - 1,
0N/A "Shouldn't be possible...");
0N/A return true;
0N/A }
0N/A }
0N/A // We fail; a completing pop_global gets the element. But the queue is
0N/A // empty (and top is greater than bottom.) Fix this representation of
0N/A // the empty queue to become the canonical one.
0N/A set_age(newAge);
0N/A assert(dirty_size(localBot, get_top()) != n() - 1,
0N/A "Shouldn't be possible...");
0N/A return false;
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueue<E>::pop_global(E& t) {
0N/A Age newAge;
0N/A Age oldAge = get_age();
0N/A juint localBot = _bottom;
0N/A juint n_elems = size(localBot, oldAge.top());
0N/A if (n_elems == 0) {
0N/A return false;
0N/A }
0N/A t = _elems[oldAge.top()];
0N/A newAge = oldAge;
0N/A newAge._top = increment_index(newAge.top());
0N/A if ( newAge._top == 0 ) newAge._tag++;
0N/A Age resAge;
0N/A *(jint*)&resAge = Atomic::cmpxchg(*(jint*)&newAge, (volatile jint*)&_age, *(jint*)&oldAge);
0N/A // Note that using "_bottom" here might fail, since a pop_local might
0N/A // have decremented it.
0N/A assert(dirty_size(localBot, newAge._top) != n() - 1,
0N/A "Shouldn't be possible...");
0N/A return (resAge == oldAge);
0N/A}
0N/A
0N/Atemplate<class E>
0N/AGenericTaskQueue<E>::~GenericTaskQueue() {
0N/A FREE_C_HEAP_ARRAY(E, _elems);
0N/A}
0N/A
0N/A// Inherits the typedef of "Task" from above.
0N/Aclass TaskQueueSetSuper: public CHeapObj {
0N/Aprotected:
0N/A static int randomParkAndMiller(int* seed0);
0N/Apublic:
0N/A // Returns "true" if some TaskQueue in the set contains a task.
0N/A virtual bool peek() = 0;
0N/A};
0N/A
0N/Atemplate<class E> class GenericTaskQueueSet: public TaskQueueSetSuper {
0N/Aprivate:
0N/A int _n;
0N/A GenericTaskQueue<E>** _queues;
0N/A
0N/Apublic:
0N/A GenericTaskQueueSet(int n) : _n(n) {
0N/A typedef GenericTaskQueue<E>* GenericTaskQueuePtr;
0N/A _queues = NEW_C_HEAP_ARRAY(GenericTaskQueuePtr, n);
0N/A guarantee(_queues != NULL, "Allocation failure.");
0N/A for (int i = 0; i < n; i++) {
0N/A _queues[i] = NULL;
0N/A }
0N/A }
0N/A
0N/A bool steal_1_random(int queue_num, int* seed, E& t);
0N/A bool steal_best_of_2(int queue_num, int* seed, E& t);
0N/A bool steal_best_of_all(int queue_num, int* seed, E& t);
0N/A
0N/A void register_queue(int i, GenericTaskQueue<E>* q);
0N/A
0N/A GenericTaskQueue<E>* queue(int n);
0N/A
0N/A // The thread with queue number "queue_num" (and whose random number seed
0N/A // is at "seed") is trying to steal a task from some other queue. (It
0N/A // may try several queues, according to some configuration parameter.)
0N/A // If some steal succeeds, returns "true" and sets "t" the stolen task,
0N/A // otherwise returns false.
0N/A bool steal(int queue_num, int* seed, E& t);
0N/A
0N/A bool peek();
0N/A};
0N/A
0N/Atemplate<class E>
0N/Avoid GenericTaskQueueSet<E>::register_queue(int i, GenericTaskQueue<E>* q) {
0N/A assert(0 <= i && i < _n, "index out of range.");
0N/A _queues[i] = q;
0N/A}
0N/A
0N/Atemplate<class E>
0N/AGenericTaskQueue<E>* GenericTaskQueueSet<E>::queue(int i) {
0N/A return _queues[i];
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueueSet<E>::steal(int queue_num, int* seed, E& t) {
0N/A for (int i = 0; i < 2 * _n; i++)
0N/A if (steal_best_of_2(queue_num, seed, t))
0N/A return true;
0N/A return false;
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueueSet<E>::steal_best_of_all(int queue_num, int* seed, E& t) {
0N/A if (_n > 2) {
0N/A int best_k;
0N/A jint best_sz = 0;
0N/A for (int k = 0; k < _n; k++) {
0N/A if (k == queue_num) continue;
0N/A jint sz = _queues[k]->size();
0N/A if (sz > best_sz) {
0N/A best_sz = sz;
0N/A best_k = k;
0N/A }
0N/A }
0N/A return best_sz > 0 && _queues[best_k]->pop_global(t);
0N/A } else if (_n == 2) {
0N/A // Just try the other one.
0N/A int k = (queue_num + 1) % 2;
0N/A return _queues[k]->pop_global(t);
0N/A } else {
0N/A assert(_n == 1, "can't be zero.");
0N/A return false;
0N/A }
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueueSet<E>::steal_1_random(int queue_num, int* seed, E& t) {
0N/A if (_n > 2) {
0N/A int k = queue_num;
0N/A while (k == queue_num) k = randomParkAndMiller(seed) % _n;
0N/A return _queues[2]->pop_global(t);
0N/A } else if (_n == 2) {
0N/A // Just try the other one.
0N/A int k = (queue_num + 1) % 2;
0N/A return _queues[k]->pop_global(t);
0N/A } else {
0N/A assert(_n == 1, "can't be zero.");
0N/A return false;
0N/A }
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueueSet<E>::steal_best_of_2(int queue_num, int* seed, E& t) {
0N/A if (_n > 2) {
0N/A int k1 = queue_num;
0N/A while (k1 == queue_num) k1 = randomParkAndMiller(seed) % _n;
0N/A int k2 = queue_num;
0N/A while (k2 == queue_num || k2 == k1) k2 = randomParkAndMiller(seed) % _n;
0N/A // Sample both and try the larger.
0N/A juint sz1 = _queues[k1]->size();
0N/A juint sz2 = _queues[k2]->size();
0N/A if (sz2 > sz1) return _queues[k2]->pop_global(t);
0N/A else return _queues[k1]->pop_global(t);
0N/A } else if (_n == 2) {
0N/A // Just try the other one.
0N/A int k = (queue_num + 1) % 2;
0N/A return _queues[k]->pop_global(t);
0N/A } else {
0N/A assert(_n == 1, "can't be zero.");
0N/A return false;
0N/A }
0N/A}
0N/A
0N/Atemplate<class E>
0N/Abool GenericTaskQueueSet<E>::peek() {
0N/A // Try all the queues.
0N/A for (int j = 0; j < _n; j++) {
0N/A if (_queues[j]->peek())
0N/A return true;
0N/A }
0N/A return false;
0N/A}
0N/A
0N/A// A class to aid in the termination of a set of parallel tasks using
0N/A// TaskQueueSet's for work stealing.
0N/A
0N/Aclass ParallelTaskTerminator: public StackObj {
0N/Aprivate:
0N/A int _n_threads;
0N/A TaskQueueSetSuper* _queue_set;
0N/A jint _offered_termination;
0N/A
0N/A bool peek_in_queue_set();
0N/Aprotected:
0N/A virtual void yield();
0N/A void sleep(uint millis);
0N/A
0N/Apublic:
0N/A
0N/A // "n_threads" is the number of threads to be terminated. "queue_set" is a
0N/A // queue sets of work queues of other threads.
0N/A ParallelTaskTerminator(int n_threads, TaskQueueSetSuper* queue_set);
0N/A
0N/A // The current thread has no work, and is ready to terminate if everyone
0N/A // else is. If returns "true", all threads are terminated. If returns
0N/A // "false", available work has been observed in one of the task queues,
0N/A // so the global task is not complete.
0N/A bool offer_termination();
0N/A
0N/A // Reset the terminator, so that it may be reused again.
0N/A // The caller is responsible for ensuring that this is done
0N/A // in an MT-safe manner, once the previous round of use of
0N/A // the terminator is finished.
0N/A void reset_for_reuse();
0N/A
0N/A};
0N/A
0N/A#define SIMPLE_STACK 0
0N/A
0N/Atemplate<class E> inline bool GenericTaskQueue<E>::push(E t) {
0N/A#if SIMPLE_STACK
0N/A juint localBot = _bottom;
0N/A if (_bottom < max_elems()) {
0N/A _elems[localBot] = t;
0N/A _bottom = localBot + 1;
0N/A return true;
0N/A } else {
0N/A return false;
0N/A }
0N/A#else
0N/A juint localBot = _bottom;
0N/A assert((localBot >= 0) && (localBot < n()), "_bottom out of range.");
0N/A jushort top = get_top();
0N/A juint dirty_n_elems = dirty_size(localBot, top);
0N/A assert((dirty_n_elems >= 0) && (dirty_n_elems < n()),
0N/A "n_elems out of range.");
0N/A if (dirty_n_elems < max_elems()) {
0N/A _elems[localBot] = t;
0N/A _bottom = increment_index(localBot);
0N/A return true;
0N/A } else {
0N/A return push_slow(t, dirty_n_elems);
0N/A }
0N/A#endif
0N/A}
0N/A
0N/Atemplate<class E> inline bool GenericTaskQueue<E>::pop_local(E& t) {
0N/A#if SIMPLE_STACK
0N/A juint localBot = _bottom;
0N/A assert(localBot > 0, "precondition.");
0N/A localBot--;
0N/A t = _elems[localBot];
0N/A _bottom = localBot;
0N/A return true;
0N/A#else
0N/A juint localBot = _bottom;
0N/A // This value cannot be n-1. That can only occur as a result of
0N/A // the assignment to bottom in this method. If it does, this method
0N/A // resets the size( to 0 before the next call (which is sequential,
0N/A // since this is pop_local.)
0N/A juint dirty_n_elems = dirty_size(localBot, get_top());
0N/A assert(dirty_n_elems != n() - 1, "Shouldn't be possible...");
0N/A if (dirty_n_elems == 0) return false;
0N/A localBot = decrement_index(localBot);
0N/A _bottom = localBot;
0N/A // This is necessary to prevent any read below from being reordered
0N/A // before the store just above.
0N/A OrderAccess::fence();
0N/A t = _elems[localBot];
0N/A // This is a second read of "age"; the "size()" above is the first.
0N/A // If there's still at least one element in the queue, based on the
0N/A // "_bottom" and "age" we've read, then there can be no interference with
0N/A // a "pop_global" operation, and we're done.
0N/A juint tp = get_top();
0N/A if (size(localBot, tp) > 0) {
0N/A assert(dirty_size(localBot, tp) != n() - 1,
0N/A "Shouldn't be possible...");
0N/A return true;
0N/A } else {
0N/A // Otherwise, the queue contained exactly one element; we take the slow
0N/A // path.
0N/A return pop_local_slow(localBot, get_age());
0N/A }
0N/A#endif
0N/A}
0N/A
0N/Atypedef oop Task;
0N/Atypedef GenericTaskQueue<Task> OopTaskQueue;
0N/Atypedef GenericTaskQueueSet<Task> OopTaskQueueSet;
0N/A
113N/A
113N/A#define COMPRESSED_OOP_MASK 1
113N/A
113N/A// This is a container class for either an oop* or a narrowOop*.
113N/A// Both are pushed onto a task queue and the consumer will test is_narrow()
113N/A// to determine which should be processed.
113N/Aclass StarTask {
113N/A void* _holder; // either union oop* or narrowOop*
113N/A public:
113N/A StarTask(narrowOop *p) { _holder = (void *)((uintptr_t)p | COMPRESSED_OOP_MASK); }
113N/A StarTask(oop *p) { _holder = (void*)p; }
113N/A StarTask() { _holder = NULL; }
113N/A operator oop*() { return (oop*)_holder; }
113N/A operator narrowOop*() {
113N/A return (narrowOop*)((uintptr_t)_holder & ~COMPRESSED_OOP_MASK);
113N/A }
113N/A
113N/A // Operators to preserve const/volatile in assignments required by gcc
113N/A void operator=(const volatile StarTask& t) volatile { _holder = t._holder; }
113N/A
113N/A bool is_narrow() const {
113N/A return (((uintptr_t)_holder & COMPRESSED_OOP_MASK) != 0);
113N/A }
113N/A};
113N/A
0N/Atypedef GenericTaskQueue<StarTask> OopStarTaskQueue;
0N/Atypedef GenericTaskQueueSet<StarTask> OopStarTaskQueueSet;
0N/A
0N/Atypedef size_t ChunkTask; // index for chunk
0N/Atypedef GenericTaskQueue<ChunkTask> ChunkTaskQueue;
0N/Atypedef GenericTaskQueueSet<ChunkTask> ChunkTaskQueueSet;
0N/A
0N/Aclass ChunkTaskQueueWithOverflow: public CHeapObj {
0N/A protected:
0N/A ChunkTaskQueue _chunk_queue;
0N/A GrowableArray<ChunkTask>* _overflow_stack;
0N/A
0N/A public:
0N/A ChunkTaskQueueWithOverflow() : _overflow_stack(NULL) {}
0N/A // Initialize both stealable queue and overflow
0N/A void initialize();
0N/A // Save first to stealable queue and then to overflow
0N/A void save(ChunkTask t);
0N/A // Retrieve first from overflow and then from stealable queue
0N/A bool retrieve(ChunkTask& chunk_index);
0N/A // Retrieve from stealable queue
0N/A bool retrieve_from_stealable_queue(ChunkTask& chunk_index);
0N/A // Retrieve from overflow
0N/A bool retrieve_from_overflow(ChunkTask& chunk_index);
0N/A bool is_empty();
0N/A bool stealable_is_empty();
0N/A bool overflow_is_empty();
0N/A juint stealable_size() { return _chunk_queue.size(); }
0N/A ChunkTaskQueue* task_queue() { return &_chunk_queue; }
0N/A};
0N/A
0N/A#define USE_ChunkTaskQueueWithOverflow