Async I/O in Zig 0.16, today
Zig 0.16 shipped last month with , a cross-platform interface for I/O and concurrency. This is a big step for the ecosystem. Libraries can now be written against a standard I/O abstraction, independent of the runtime, and application developers can plug in whatever implementation they want. The only usable implementation shipped with 0.16 is , which uses a thread pool. When you spawn concurrent tasks, it creates OS threads to run them. Let’s see how it works with a simple example: This spawns 10,000 concurrent tasks, each sleeping for 10 seconds. On my machine, it completes in about 20 seconds: The overhead comes from spawning OS threads. If you try increasing this to 50,000 tasks, it will likely fail on most systems due to thread limits ( on Linux). This isn’t just an arbitrary benchmark. Asynchronous I/O exists to solve a real problem: network servers with many connected clients. You don’t want to spawn an OS thread for every client connection. That’s why we have event loops, coroutines, and async I/O. There is in the standard library, which is meant to use io_uring on Linux and kqueue on BSD/macOS. It’s still a work in progress though, missing many functions and doesn’t currently compile. I’ve written about zio before , and I’ve just released version 0.11 with a full implementation. It uses stackful coroutines and asynchronous OS-level I/O APIs (io_uring or epoll on Linux, kqueue on BSD/macOS, IOCP on Windows). Here’s the same example using zio: The code is almost identical. You just initialize a zio runtime and use its method to get the interface. With zio, the same 10,000 tasks complete in about 10 seconds: That’s the expected time, since all tasks run truly concurrently. You can increase this to 50,000 or more tasks and it will continue to work, limited only by available memory. You can use this instance for anything you’d use for. To write an HTTP server with , for example, just pass zio’s and it will work the same way. If you want to use async I/O in Zig 0.16 with the standard APIs, you don’t need to wait for to be ready. Zio’s implementation is still new, so if you hit any problems, please reach out on GitHub and I’ll be happy to help.