I have understood that one major advantage of asynchronous functions is that fewer threads reduces context switches. However, when I compare context switches between synchronous and asynchronous programming, I find that fewer threads only eliminates context switches from thread scheduling.
Below I lay out when I think context switches occur. I have not verified that these steps are correct.
Context switches with synchronous calls
- User thread runs.
- User thread reaches
write
function call. - User thread traps into kernel mode. (context switch)
- OS performs write.
- OS returns control to some other thread. Back to step 1. (context switch)
Context switches with asynchronous calls
Assume there is only one user thread running.
- Single user thread runs.
- User thread reaches
async_write
function call. - User thread traps into kernel mode. (context switch)
- OS schedules write.
- OS returns control to user thread. Back to step 1. (context switch)
The Question
In either of the above examples, there are two context switches. Asynchronous programming is not reducing the number of context switches. What am I missing?