2020/04/06

Rust Sync/Await

This blog https://os.phil-opp.com/async-await/ explains well the underlying mechanism of Rust sync and await.

Some useful quote of this long blog that helps to:
- Get an general idea of underlying mechanism
- How to use async/await

Quotes starts from here:
----------------------------------

There are two forms of multitasking: Cooperative, Preemptive multitasking.
The disadvantage of preemption is that each task requires its own stack. Compared to a shared stack, this results in a higher memory usage per task and often limits the number of tasks in the system.

cooperative multitasking lets each task run until it voluntarily gives up control of the CPU.
The idea is that either the programmer or the compiler inserts yield operations into the program.

The idea behind async/await is to let the programmer write code that looks like normal synchronous code, but is turned into asynchronous code by the compiler.

What the compiler does behind this scenes is to transform the body of the async function into a state machine, with each .await call representing a different state.

With a single future, we can always wait for each future manually using a loop as described above. However, this approach is very inefficient and not practical for programs that create a large number of futures.
The purpose of an executor is to allow spawning futures as independent tasks, typically through some sort of spawn method. The executor is then responsible for polling all futures until they are completed. The big advantage of managing all futures in a central place is that the executor can switch to a different future whenever a future returns Poll::Pending. Thus, asynchronous operations are run in parallel and the CPU is kept busy.
Many executor implementations can also take advantage of systems with multiple CPU cores. They create a thread pool that is able to utilize all cores if there is enough work available and use techniques such as work stealing to balance the load between cores. There are also special executor implementations for embedded systems that optimize for low latency and memory overhead.

----------------------------------



Post Code on Blogger

Simplest way to post code to blogger for me: <pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black;overflow-x:...