event: implement pollEvent and tryEvent

Implement a way for an application to poll the event loop in a blocking
way without popping an event. Implement a non-blocking pop. These
together enable an application to poll the event loop and then drain it.
This is useful when lots of events are delivered in a short amount of
time so an application can batch process the events and then render.

Signed-off-by: Tim Culverhouse <tim@timculverhouse.com>
This commit is contained in:
Tim Culverhouse 2024-03-11 09:24:42 -05:00
parent 22af4908a1
commit cecf774ed2
2 changed files with 21 additions and 0 deletions

View file

@ -87,6 +87,16 @@ pub fn Queue(
return self.pop(); return self.pop();
} }
/// Poll the queue. This call blocks until events are in the queue
pub fn poll(self: *Self) void {
self.mutex.lock();
defer self.mutex.unlock();
while (self.isEmptyLH()) {
self.not_empty.wait(&self.mutex);
}
std.debug.assert(!self.isEmptyLH());
}
fn isEmptyLH(self: Self) bool { fn isEmptyLH(self: Self) bool {
return self.write_index == self.read_index; return self.write_index == self.read_index;
} }

View file

@ -146,6 +146,17 @@ pub fn Vaxis(comptime T: type) type {
return self.queue.pop(); return self.queue.pop();
} }
/// blocks until an event is available. Useful when your application is
/// operating on a poll + drain architecture (see tryEvent)
pub fn pollEvent(self: *Self) void {
self.queue.poll();
}
/// returns an event if one is available, otherwise null. Non-blocking.
pub fn tryEvent(self: *Self) ?Event {
return self.queue.tryPop();
}
/// posts an event into the event queue. Will block if there is not /// posts an event into the event queue. Will block if there is not
/// capacity for the event /// capacity for the event
pub fn postEvent(self: *Self, event: T) void { pub fn postEvent(self: *Self, event: T) void {