logoalt Hacker News

nemothekidtoday at 1:02 AM1 replyview on HN

I think I'm missing something here, but the most interesting piece here is how would stackless coroutines work in Zig?

Since any function can be turned into a coroutine, is the red/blue problem being moved into the compiler? If I call:

     io.async(saveFileA, .{io});
Is that a function call? Or is that some "struct" that gets allocated on the stack and passed into an event loop?

Furthermore, I guess if you are dealing with pure zig, then its fine, but if you use any FFI, you can potentially end up issuing a blocking syscall anyways.


Replies

laserbeamtoday at 1:32 AM

I hope this is not a bad answer as I tried to understand what stackless coroutines even are for the past week.

1. Zig plans to annotate the maximum possible stack size of a function call https://github.com/ziglang/zig/issues/23367 . As people say, this would give the compiler enough information to implemented stackless coroutines. I do not understand well enough why that’s the case.

2. Allegedly, this is only possible because zig uses a single compilation unit. You are very rarely dealing with modules that are compiled independently. If a function in zig is not called, it’s not compiled. I can see how this helps with point 1.

3. Across FFI boundaries this is a problem in every language. In theory you can always do dumb things after calling into a shared library. A random C lib can always spawn threads and do things the caller isn’t expecting. You need unsafe blocks in rust for the same reason.

4. In theory, zig controls the C std library when compiling C code. In some cases, if there’s only one Io implementation used for example, zig could replace functions in the c std library to use that io vtable instead.

Regardless, I kinda wish kristoff/andrew went over what stackless coroutines are (for dummies) in an article at some point. I am unsure people are talking about the same thing when mentioning that term. I am happy to wait for that article until zig tries to implement that using the new async model.

show 1 reply