diff --git a/src/hxcoro/schedulers/ThreadAwareScheduler.hx b/src/hxcoro/schedulers/ThreadAwareScheduler.hx index 0f935f70..f490f3c4 100644 --- a/src/hxcoro/schedulers/ThreadAwareScheduler.hx +++ b/src/hxcoro/schedulers/ThreadAwareScheduler.hx @@ -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; - - public function new() { - read = write = 0; - storage = CircularVector.create(1); - } -} - -private class CircularQueue { - var read:Int; - var write:Int; - var storage:CircularVector; - - 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; private class ThreadQueue { public final queue:TlsQueue; @@ -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)); @@ -198,7 +149,8 @@ class ThreadAwareScheduler implements IScheduler implements ILoop { var event:Null; 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; } @@ -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'); diff --git a/src/hxcoro/thread/WorkStealingQueue.hx b/src/hxcoro/thread/WorkStealingQueue.hx index 15301420..ba9900a3 100644 --- a/src/hxcoro/thread/WorkStealingQueue.hx +++ b/src/hxcoro/thread/WorkStealingQueue.hx @@ -1,14 +1,38 @@ 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 { + public final slots:CircularVector; + + public function new(slots:CircularVector) { + 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 { final read:AtomicInt; final write:AtomicInt; - var storage:CircularVector; + final storage:AtomicObject>; /** Creates a new work-stealing queue. @@ -16,36 +40,49 @@ class WorkStealingQueue { 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 { + 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 { + return storage.load(); + } + + function resize(slots:CircularVector, 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); } /** @@ -53,8 +90,9 @@ class WorkStealingQueue { `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(); @@ -63,8 +101,7 @@ class WorkStealingQueue { 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 { @@ -78,13 +115,14 @@ class WorkStealingQueue { 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(""); } -} \ No newline at end of file +} diff --git a/tests/src/schedulers/TestThreadAwareScheduler.hx b/tests/src/schedulers/TestThreadAwareScheduler.hx new file mode 100644 index 00000000..6d6b5373 --- /dev/null +++ b/tests/src/schedulers/TestThreadAwareScheduler.hx @@ -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 +}