Skip to content

loop: add some comment on reset functions #305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 9, 2025
Merged
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
25 changes: 15 additions & 10 deletions src/loop.zig
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,12 @@ const log = std.log.scoped(.loop);
pub const SingleThreaded = struct {
alloc: std.mem.Allocator, // TODO: unmanaged version ?
io: IO,

// both events_nb are used to track how many callbacks are to be called.
// We use these counters to wait until all the events are finished.
js_events_nb: usize,
zig_events_nb: usize,

cbk_error: bool = false,

// js_ctx_id is incremented each time the loop is reset for JS.
Expand Down Expand Up @@ -79,6 +83,12 @@ pub const SingleThreaded = struct {
}

pub fn deinit(self: *Self) void {
// first disable callbacks for existing events.
// We don't want a callback re-create a setTimeout, it could create an
// infinite loop on wait for events.
self.resetJS();
self.resetZig();

// run tail events. We do run the tail events to ensure all the
// contexts are correcly free.
while (self.eventsNb(.js) > 0 or self.eventsNb(.zig) > 0) {
Expand All @@ -88,7 +98,7 @@ pub const SingleThreaded = struct {
};
}
if (comptime CANCEL_SUPPORTED) {
self.cancelAll();
self.io.cancel_all();
}
self.io.deinit();
self.cancel_pool.deinit();
Expand Down Expand Up @@ -138,9 +148,6 @@ pub const SingleThreaded = struct {
fn eventsNb(self: *Self, comptime event: Event) usize {
return @atomicLoad(usize, self.eventsPtr(event), .seq_cst);
}
fn resetEvents(self: *Self, comptime event: Event) void {
@atomicStore(usize, self.eventsPtr(event), 0, .unordered);
}

// JS callbacks APIs
// -----------------
Expand Down Expand Up @@ -284,19 +291,17 @@ pub const SingleThreaded = struct {
self.io.cancel_one(*ContextCancel, ctx, cancelCallback, completion, comp_cancel);
}

fn cancelAll(self: *Self) void {
self.resetEvents(.js);
self.resetEvents(.zig);
self.io.cancel_all();
}

// Reset all existing JS callbacks.
// The existing events will happen and their memory will be cleanup but the
// corresponding callbacks will not be called.
pub fn resetJS(self: *Self) void {
self.js_ctx_id += 1;
self.cancelled.clearRetainingCapacity();
}

// Reset all existing Zig callbacks.
// The existing events will happen and their memory will be cleanup but the
// corresponding callbacks will not be called.
pub fn resetZig(self: *Self) void {
self.zig_ctx_id += 1;
}
Expand Down