Skip to content

andreast12/advprog-module10-timer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Asynchronous Output Explanation

Asynchronous Output

This order is due to how asynchronous programming works in Rust:

  • println!("Andreas' Computer: hey hey"); runs immediately in the main thread, so it prints first.
  • The line spawner.spawn(async { ... }) schedules an async task that prints "howdy!", waits asynchronously for 2 seconds, then prints "done!". The executor runs this task:
    • "howdy!" is printed right away when the task starts.
    • The task then awaits the timer, which yields control back to the executor, allowing other tasks (if any) to run while waiting.
    • After 2 seconds, the timer completes, and the task resumes, printing "done!".

Rust's async model uses futures and an executor. The executor polls tasks and resumes them when they're ready, enabling non-blocking waits. That's why the output order reflects the immediate and delayed actions in the async task.

Multiple Spawn

Multiple spawn

When we use spawner.spawn(...), we are scheduling asynchronous tasks to be executed by the executor. The spawner is responsible for sending new tasks (futures) into the executor's queue, while the executor is responsible for polling and running these tasks to completion. Each call to spawn adds a new async task to the queue, which the executor will process in turn.

Removing Drop

Removing drop

The drop(spawner) line is important because it signals to the executor that no more tasks will be added. When the spawner is dropped, the channel used for task scheduling is closed, so the executor knows when it has finished running all tasks and can exit its loop. If you do not drop the spawner, the executor will keep waiting for new tasks, and the order in which tasks complete (especially the 'done!' messages) may vary, since the executor may continue polling tasks as long as the channel is open.

In summary, the spawner schedules tasks, the executor runs them, and dropping the spawner tells the executor when to stop. The interaction between these components determines the order and completion of asynchronous tasks in your program.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages