-
-
Notifications
You must be signed in to change notification settings - Fork 694
Description
I have kind of accepted that this class isn't going to go away, so I would like to see it improve. In its current state its a bit of a locking nightmare which shouldn't be necessary. Here's an outline of what I think would work better:
import sys.thread.Deque;
import sys.thread.Thread;
class Event {
public var next:Null<Event>;
}
class EventLoop {
final deque:Deque<Event>;
final owner:Thread;
var queue:Null<Event>;
public function new() {
deque = new Deque();
owner = Thread.current();
}
function addToQueue(e:Event) {
if(queue != null) {
queue.next = e;
} else {
queue = e;
}
}
public function start(e:Event) {
if (owner == Thread.current()) {
addToQueue(e);
} else {
deque.add(e);
}
}
function drainDeque() {
while (true) {
final current = deque.pop(false);
if (current == null) {
break;
}
addToQueue(current);
}
}
public function loopOnce() {
drainDeque();
// sortEvents();
// iterate events etc.
}
}So any site which modifies the queue like start (which I think should be renamed btw) gets a fast path if the adding thread is the owner, and otherwise pushes the event instance to a deque. That deque is then drained into the real queue in loopOnce, by the owner who I assume/hope is the only one who is allowed to loop this.
This way the only locking required is via the deque. Other threads can still add events to the queue that way, and they will be picked up on the next loopOnce.
@ncannasse Please check this out and let me know if this would cover your use-cases.