Skip to content

Commit

Permalink
event: implement pollEvent and tryEvent
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
rockorager committed Mar 11, 2024
1 parent 22af490 commit cecf774
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/queue.zig
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ pub fn Queue(
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 {
return self.write_index == self.read_index;
}
Expand Down
11 changes: 11 additions & 0 deletions src/vaxis.zig
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,17 @@ pub fn Vaxis(comptime T: type) type {
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
/// capacity for the event
pub fn postEvent(self: *Self, event: T) void {
Expand Down

0 comments on commit cecf774

Please sign in to comment.