Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 13 additions & 61 deletions src/hxcoro/schedulers/ThreadAwareScheduler.hx
Original file line number Diff line number Diff line change
Expand Up @@ -7,69 +7,20 @@ import haxe.coro.IContinuation;
import haxe.coro.schedulers.IScheduler;
import haxe.coro.schedulers.ISchedulerHandle;
import haxe.exceptions.ArgumentException;
import hxcoro.ds.CircularVector;
import hxcoro.schedulers.ILoop;
import hxcoro.thread.WorkStealingQueue;
import sys.thread.Deque;
import sys.thread.Semaphore;
import sys.thread.Thread;
import sys.thread.Tls;

private class CircularQueueData {
public var read:Int;
public var write:Int;
public var storage:CircularVector<ScheduledEvent>;

public function new() {
read = write = 0;
storage = CircularVector.create(1);
}
}

private class CircularQueue {
var read:Int;
var write:Int;
var storage:CircularVector<ScheduledEvent>;

public function new(size:Int) {
storage = CircularVector.create(size);
read = 0;
write = 0;
}

function resize(from:Int, to:Int) {
final newStorage = CircularVector.create(storage.length << 1);
for (i in from...to) {
newStorage[i] = storage[i];
}
storage = newStorage;
}

public function add(value:ScheduledEvent) {
final w = write;
final r = read;
final sizeNeeded = w - r;
if (sizeNeeded >= storage.length) {
resize(r, w);
}
storage[w] = value;
++write;
}

public function pop() {
final r = read;
final w = write;
if (w - r <= 0) {
return null;
}
return storage[read++];
}

public function toString() {
return 'CircularQueue(r $read, w $write, l ${storage.length})';
}
}

private typedef TlsQueue = CircularQueue;
/**
The queue that a thread schedules its events into. It is shared between two threads: the
thread that owns it is the only producer, and the loop thread is the only consumer. Being
a TLS value only rules out competing producers, so the queue still has to publish its
events to the loop thread, which `WorkStealingQueue` does with atomic stores and loads.
**/
private typedef TlsQueue = WorkStealingQueue<ScheduledEvent>;

private class ThreadQueue {
public final queue:TlsQueue;
Expand Down Expand Up @@ -113,7 +64,7 @@ class ThreadAwareScheduler implements IScheduler implements ILoop {
return threadQueue;
}

final newQueue = new CircularQueue(4);
final newQueue = new WorkStealingQueue();
final threadQueue = new ThreadQueue(newQueue);
final handle = Thread.addCurrentCallbacks({onExit: function() {
queueDeque.add(Remove(threadQueue));
Expand Down Expand Up @@ -198,7 +149,8 @@ class ThreadAwareScheduler implements IScheduler implements ILoop {
var event:Null<ScheduledEvent>;
while (true) {
final queue = current.queue;
event = queue.pop();
// This thread is the only consumer, so `steal` only returns null if the queue is empty.
event = queue.steal();
if (event == null) {
break;
}
Expand Down Expand Up @@ -267,8 +219,8 @@ class ThreadAwareScheduler implements IScheduler implements ILoop {
var current = firstQueue;
var totalWrites = 0;
@:privateAccess while (current != null) {
Sys.println('\tqueue: (r ${current.queue.read}, w ${current.queue.write}, l: ${current.queue.storage.length})');
totalWrites += current.queue.write;
Sys.println('\tqueue: (r ${current.queue.read.load()}, w ${current.queue.write.load()}, l: ${current.queue.loadSlots().length})');
totalWrites += current.queue.write.load();
current = current.next;
}
Sys.println('\ttotal writes: $totalWrites');
Expand Down
86 changes: 62 additions & 24 deletions src/hxcoro/thread/WorkStealingQueue.hx
Original file line number Diff line number Diff line change
@@ -1,60 +1,98 @@
package hxcoro.thread;
import haxe.atomic.AtomicInt;
import haxe.atomic.AtomicObject;
import hxcoro.ds.CircularVector;

/**
Holds the slots of a `WorkStealingQueue`. `AtomicObject` needs a class instance, and the
storage of `CircularVector` is a native array on some targets.
**/
private class Slots<T> {
public final slots:CircularVector<T>;

public function new(slots:CircularVector<T>) {
this.slots = slots;
}
}

/**
A single-producer multi-consumer work-stealing queue.

Only one thread may call `add`, but any number of threads may call `steal` concurrently,
including the producer.

The producer publishes everything it writes through atomic stores, which consumers load
before reading the data:

- A slot is written before `write` is advanced.
- On a resize, the live slots are copied into the new storage before it is stored in
`storage`. A consumer that loaded `write` before the resize can still load the new
storage afterwards, and only the atomic `storage` makes the copied slots visible to it.
**/
class WorkStealingQueue<T> {
final read:AtomicInt;
final write:AtomicInt;
var storage:CircularVector<T>;
final storage:AtomicObject<Slots<T>>;

/**
Creates a new work-stealing queue.
**/
public function new() {
read = new AtomicInt(0);
write = new AtomicInt(0);
storage = CircularVector.create(16);
storage = new AtomicObject(new Slots(CircularVector.create(16)));
}

function resize(from:Int, to:Int) {
final newStorage = CircularVector.create(storage.length << 1);
/**
Returns the current slots.
**/
function loadSlots():CircularVector<T> {
return loadHolder().slots;
}

/**
On hxcpp, `AtomicObject.load` returns an untyped `hx::Object`, so a field access directly
on its result fails to compile. The declared return type makes hxcpp convert it. This is
not inline, so the conversion can't be optimized away.
**/
function loadHolder():Slots<T> {
return storage.load();
}
Comment on lines +53 to +60

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll review this again once we've dealt with HaxeFoundation/haxe#13095 properly.


function resize(slots:CircularVector<T>, from:Int, to:Int) {
final newSlots = CircularVector.create(slots.length << 1);
for (i in from...to) {
newStorage[i] = storage[i];
newSlots[i] = slots[i];
}
return newStorage;
return newSlots;
}

/**
Adds `value` to this queue.

This function is not thread-safe. It might also cause allocations in
case the underlying storage has to be expanded.
This function must only be called by the queue's single producer thread. It might also
cause allocations in case the underlying storage has to be expanded.
**/
public function add(value:T) {
final w = write.load();
final r = read.load();
final sizeNeeded = w - r;
if (sizeNeeded >= storage.length) {
final storage = resize(r, w);
storage[w] = value;
this.storage = storage;
write.add(1);
} else {
storage[w] = value;
write.add(1);
var slots = loadSlots();
if (w - r >= slots.length) {
slots = resize(slots, r, w);
storage.store(new Slots(slots));
}
slots[w] = value;
write.add(1);
}

/**
Tries to remove an element from this queue. If no element is available,
`null` is returned.

This function is thread-safe. Note that a `null` return value does not
necessarily mean that the queue is empty, because the operation could
fail for other reasons.
necessarily mean that the queue is empty: if several threads steal at the
same time, all but one of them can get `null`. With a single consumer, it
does mean that the queue is empty.
**/
public function steal() {
final r = read.load();
Expand All @@ -63,8 +101,7 @@ class WorkStealingQueue<T> {
if (size <= 0) {
return null;
}
final storage = storage;
final v = storage[r];
final v = loadSlots()[r];
if (read.compareExchange(r, r + 1) == r) {
return v;
} else {
Expand All @@ -78,13 +115,14 @@ class WorkStealingQueue<T> {
public function dump() {
final r = read.load();
final w = write.load();
Sys.print('(r $r, w $w, l ${storage.length}): ');
final slots = loadSlots();
Sys.print('(r $r, w $w, l ${slots.length}): ');
for (i in r...w) {
if (i != r) {
Sys.print(" ");
}
Sys.print(storage.get(i));
Sys.print(slots.get(i));
}
Sys.println("");
}
}
}
52 changes: 52 additions & 0 deletions tests/src/schedulers/TestThreadAwareScheduler.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package schedulers;

// Not on neko: assigning a declared field for the first time adds it to the object, which is
// not safe while another thread reads the object. The thread pool shares continuations
// between threads like that, so this test fails there for reasons unrelated to the scheduler.
// See https://github.com/HaxeFoundation/neko/issues/335
#if (target.threaded && !neko)
import hxcoro.run.LoopRun;
import hxcoro.run.Setup;
import sys.thread.Lock;
import sys.thread.Thread;
#end

class TestThreadAwareScheduler extends atest.Test {
#if (target.threaded && !neko)
/**
Pool threads schedule their `yield` resumptions into their own queues, which the loop
thread drains. The queue's indices used to be plain fields, so the loop thread could see
an advanced write index before the event itself, and lose the event. The run then hung.
On the JVM, this happened within a few rounds.

The rounds run on a separate thread, so a hang fails the test after a deadline instead
of blocking the test run.
**/
function testYieldBurstsOnThreadPool() {
final rounds = #if (jvm || cpp) 100 #else 2 #end;
final yieldsPerTask = #if (jvm || cpp) 2000 #else 200 #end;
final done = new Lock();
Thread.create(() -> {
for (_ in 0...rounds) {
final setup = Setup.createThreadPool(4);
LoopRun.runTask(setup.loop, setup.createContext(), node -> {
for (_ in 0...32) {
node.async(_ -> {
for (_ in 0...yieldsPerTask) {
yield();
}
});
}
});
setup.close();
}
done.release();
});
Assert.isTrue(done.wait(60.0), "the run hung, so an event was lost");
}
#else
function testNotSupported() {
Assert.pass();
}
#end
}
Loading