4 ms·
Can you explain how you run an async function synchronously, and how it has no overhead compared to calling a synchronous implementation of the same function ?
by fooyc 10y ago
Can you explain how you run an async function synchronously, and how it has no overhead compared to calling a synchronous implementation of the same function ?
- Rusky 10y agoAs far as the kernel-side implementation goes, IO is always asynchronous. The CPU is not involved in the actual movement of data between memory and the network interface. When you make a synchronous syscall, the kernel initiates the operation, saves the state of your thread, and starts another one. When the network interface is done, it signals the kernel, which then marks your thread as runnable and schedules it for execution. When you make an asynchronous syscall, the kernel initiates the operation but does not block your thread. This is usually done in the context of an event loop, which makes a synchronous syscall (like epoll_wait) when it runs out of tasks to run. Thus, converting a single async syscall to a sync one means two syscalls: initiate the operation, then wait for its result. The extra round trip between user and kernel mode is basically free in this case because you're blocking on IO, and any logic it implements has to happen in the synchronous case anyway.
- fooyc 10y agoYou are side-stepping the question by explaining how scheduling works. You can not say that there is NO overhead. Using async code in a synchronous fashion is not going to be as fast as using plain sync code. Look at the wait() function: https://github.com/alexcrichton/futures-rs/blob/master/src/future/mod.rs#L270-L274 https://github.com/alexcrichton/futures-rs/blob/master/src/f... All this code IS overhead that wouldn't exist if the code was synchronous in the first place.