zigroutines
zigroutines is a library that brings stackful M:N concurrency to Zig, inspired by Go’s task model, channels, and select, but with a philosophy that fits Zig perfectly: nothing global, nothing hidden, pay only for what you enable.
You construct a Runtime with your chosen scheduler (FIFO, work‑stealing, priority, or even 1:1 OS threads), I/O backend (poll, IOCP, io_uring, or none), and optional metrics. Every task gets a fixed 2 KiB stack (no silent growth, no per‑task configuration) - deep recursion and large buffers go on the heap. The library provides:
- CSP:
Channel(T)with rendezvous/buffered, multi‑armselect(up to 32 arms each for send/recv), backpressure policies (drop_newest,drop_oldest, …). - Structured concurrency:
Scope/Nurserywith deadlines and cooperative cancellation. - Synchronisation primitives that park the task, not the OS thread: Mutex, RwLock, Semaphore, RateLimiter, Notify, Watch(T).
- Pluggable I/O - integrate
poll, IOCP, or io_uring only when you need it. - Observability - optional atomic metrics and tracing hooks.
Design decisions:
The most interesting challenge was deciding what not to hide. I deliberately avoided a global runtime - every Runtime is explicit, so you can embed it into your own event loop or run multiple independent runtimes. This also makes it easy to test and reason about resource usage.
Another key decision: fixed‑size stacks (2 KiB). This is a trade‑off - you lose the flexibility of growing stacks, but you gain predictability and avoid GC‑like copying. To compensate, the library provides a spawnLeaf for stackless, run‑to‑completion work, and the stack pool + guard page/canary give you control over overflow and memory usage.
I also made I/O a plugin - the core scheduler doesn’t assume a net‑poller. This keeps the runtime tiny for CPU‑bound tasks, and you enable I/O only when needed.
Finally, the cancellation model is cooperative - you poll a CancelToken or use select with a cancel arm. This avoids the complexity and unpredictability of preemptive cancellation, and fits well with the explicit nature of the library.
AI / LLM usage disclosure
I used an LLM (Grok) only to the
README.mdfile and to generatecode‑review summarie
Supported Zig versions
0.16 and 0.17‑dev