by the_duke · 3y ago · 0 comments
Doing more work in a single thread saves a lot of context switches, especially if IO makes up a large portion of the workload. And even more so with other mechanisms to minimize syscalls, like io_uring on Linux.
Async overhead is highly dependent on the way the async runtime is implemented.
It's true that async requires scheduling and task switching to be implemented in userspace, but assuming that async is used as an alternative to threads, then the OS would be doing a similar amount of work anyway.
The OS may be able to do that more efficiently because it has more information about the system. Or it may be the opposite, because the application has more information about the workloads.
"async = overhead" as a general statement is not correct.
And kernel mode actually has much more efficient and performant context switches, because the kernel can access hardware directly.
(It is sometimes useful to be able to do custom user mode scheduling, but certainly not because of "context switches".)
In my experience, the exact opposite is true, particularly in the era of CPU mitigations that require TLB flushes upon every kernel-mode context switch.
User-level can also have the advantage of having more actual context about the task that is running, meaning that it's often able to avoid saving/restoring as much data as a kernel-level switch would. See Go's green threads for a great example of this kind of cooperation between runtime and language.
> Do you have a citation for kernel mode having more efficient context switches? What kind of direct hardware access are you referring to that would be better than pushing the register context onto the stack?
The closest thing to this that I can think of is on 32-bit x86 which did have hardware assisted context switching via TSRs.
As it happens, everybody stopped using it because it was too slow, and a bit painful unless you fully bought into x86's awful segmentation model. Early Linux kernels use it if you want to see it in action.
This is unrelated to kernel threading.
If you have 1 thread handling 1000 requests with some async io mechanism (epoll, io_uring, ...) ,instead of 1000 threads each handling one request, there are much fewer threads fighting over CPU cores and the 1 thread can stay active much longer, hence reducing the amount of context switches.
Especially with a mechanism like io_uring, which helps minimize syscalls (and hence switching to kernel threads).
(When the kernel decides which thread gets to run it's doing the equivalent of an epoll call.)