@@ -33,8 +33,12 @@ const log = std.log.scoped(.loop);
33
33
pub const SingleThreaded = struct {
34
34
alloc : std.mem.Allocator , // TODO: unmanaged version ?
35
35
io : IO ,
36
+
37
+ // both events_nb are used to track how many callbacks are to be called.
38
+ // We use these counters to wait until all the events are finished.
36
39
js_events_nb : usize ,
37
40
zig_events_nb : usize ,
41
+
38
42
cbk_error : bool = false ,
39
43
40
44
// js_ctx_id is incremented each time the loop is reset for JS.
@@ -79,6 +83,12 @@ pub const SingleThreaded = struct {
79
83
}
80
84
81
85
pub fn deinit (self : * Self ) void {
86
+ // first disable callbacks for existing events.
87
+ // We don't want a callback re-create a setTimeout, it could create an
88
+ // infinite loop on wait for events.
89
+ self .resetJS ();
90
+ self .resetZig ();
91
+
82
92
// run tail events. We do run the tail events to ensure all the
83
93
// contexts are correcly free.
84
94
while (self .eventsNb (.js ) > 0 or self .eventsNb (.zig ) > 0 ) {
@@ -88,7 +98,7 @@ pub const SingleThreaded = struct {
88
98
};
89
99
}
90
100
if (comptime CANCEL_SUPPORTED ) {
91
- self .cancelAll ();
101
+ self .io . cancel_all ();
92
102
}
93
103
self .io .deinit ();
94
104
self .cancel_pool .deinit ();
@@ -138,9 +148,6 @@ pub const SingleThreaded = struct {
138
148
fn eventsNb (self : * Self , comptime event : Event ) usize {
139
149
return @atomicLoad (usize , self .eventsPtr (event ), .seq_cst );
140
150
}
141
- fn resetEvents (self : * Self , comptime event : Event ) void {
142
- @atomicStore (usize , self .eventsPtr (event ), 0 , .unordered );
143
- }
144
151
145
152
// JS callbacks APIs
146
153
// -----------------
@@ -284,19 +291,17 @@ pub const SingleThreaded = struct {
284
291
self .io .cancel_one (* ContextCancel , ctx , cancelCallback , completion , comp_cancel );
285
292
}
286
293
287
- fn cancelAll (self : * Self ) void {
288
- self .resetEvents (.js );
289
- self .resetEvents (.zig );
290
- self .io .cancel_all ();
291
- }
292
-
293
294
// Reset all existing JS callbacks.
295
+ // The existing events will happen and their memory will be cleanup but the
296
+ // corresponding callbacks will not be called.
294
297
pub fn resetJS (self : * Self ) void {
295
298
self .js_ctx_id += 1 ;
296
299
self .cancelled .clearRetainingCapacity ();
297
300
}
298
301
299
302
// Reset all existing Zig callbacks.
303
+ // The existing events will happen and their memory will be cleanup but the
304
+ // corresponding callbacks will not be called.
300
305
pub fn resetZig (self : * Self ) void {
301
306
self .zig_ctx_id += 1 ;
302
307
}
0 commit comments