-
-
Save charles-l/614cb56719eeab67c14c0faca61a4246 to your computer and use it in GitHub Desktop.
`@Frame` question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const Coroutines = struct { | |
allocator: std.mem.Allocator, | |
frame_pointers: std.ArrayList(anyframe), | |
const Self = @This(); | |
fn init(allocator: std.mem.Allocator) Self { | |
return Self{ | |
.allocator = allocator, | |
.frame_pointers = std.ArrayList(anyframe).init(allocator), | |
}; | |
} | |
fn deinit(self: *Self) void { | |
self.frame_pointers.deinit(); | |
} | |
fn yield(self: *Self, fr: anytype) void { | |
const T = @typeInfo(@TypeOf(fr)).Pointer.child; | |
var frame_ptr = gpa.allocator().create(T) catch unreachable; | |
frame_ptr.* = fr.*; | |
self.frame_pointers.append(frame_ptr) catch @panic("couldn't push coroutine"); | |
} | |
fn resumeAll(self: *Self) void { | |
// store the bytes for the current coroutines | |
var cos = self.frame_pointers.clone() catch @panic("blarg"); | |
defer cos.clearAndFree(); // delete old coroutine frame pointers after we're done | |
// clear for the next batch of coroutines | |
self.frame_pointers.clearRetainingCapacity(); | |
// run them all | |
for (cos.items) |co| { | |
resume co; | |
} | |
// I can't free the frames here: | |
// for (cos.items) |co| { | |
// self.allocator.destroy(@ptrCast([*]align(8) const u8, co)); | |
// } | |
} | |
}; | |
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
var coroutines = Coroutines.init(gpa.allocator()); | |
fn fun() void { | |
std.debug.print("fun\n", .{}); | |
suspend { | |
coroutines.yield(@frame()); | |
} | |
} | |
pub fn level_5() void { | |
std.debug.print("level 5\n", .{}); | |
for ([_]u8{ 1, 2 }) |_| { | |
suspend { | |
coroutines.yield(@frame()); | |
} | |
fun(); | |
} | |
} | |
pub fn main() void { | |
_ = async level_5(); | |
defer std.debug.assert(!gpa.deinit()); | |
while (coroutines.frame_pointers.items.len > 0) { | |
std.debug.print("main loop\n", .{}); | |
coroutines.resumeAll(); | |
} | |
coroutines.deinit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment