by diarrhea · 3y ago · 0 comments
The article mentions how non-blocking IO is the way to gain back control otherwise conceded to the kernel in the case of blocking IO. However, non-blocking IO has to be laboriously implemented in user code. Is that true still? What if we used the threading model but relied on io_uring?
Note that the io_uring approach isn't too different (just more universalized) than how Windows has always implemented async operations (with overlapped and io completion ports). Code written for that environment originally just used the event loop model but it's easier/better ergonomics to wrap it in async and use that instead (e.g. how C#'s async/await works) because you can avoid callback hell, state passing, etc. and just write code "linearly" with cooperative yield points invisibly stashing and retrieving the "stack" for you.
Whilst you can do this, I still think the best approach is “actual-async”. The idea of “spin up this worker and shunt the data across to it just so it can block” strikes me as somewhat wasteful. If you know you’re going to have to wait, you’re better off not expending resources doing so, and instead use the time to do useful work instead.
It doesn't make any sense to say 'use the time to do useful work instead'. That's what you do when you block: in a threaded model, when you block you do 'io_uring_get_sqe', 'io_uring_prep_read' (or whatever), 'io_uring_set_userdata' 'io_uring_submit' and then you switch contexts (with <ucontext.h> or some equivalent) to another thread that is ready. When you have no ready threads you just call 'io_uring_wait_cqe', and for each completion you do 'io_uring_get_userdata', get a pointer to the thread, record the result of the operation and append the thread to a runqueue to be resumed.
From the perspective of the thread, you write
int e = read(fd, buf, sizeof buf);
if (e < 0) err(1, "read: %s", strerror(-e));
and it all feels completely sequential. Underneath it is stackful coroutines.