(Tasks = Green Thread) != OS Thread
-
Tasks are not threads, these are light weight threads created by runtime.
These are non-blocking & task may or may not execute on seperate thread.
2 tasks run concurrently.
Creating Tasks
-
tokio::main macro we can create main async.
tokio::spawn() create concurrent task
tokio::spawn() //Green Thread | tokio::task::spawn_blocking | executor::block_on |
---|---|---|
- spawn Non-blocking tasks within tokio runtime - Main thread will wait on JoinHandle(same as pthread_join)
|
Spawn a blocking task into a separate thread from the Tokio runtime
|
|
Comparison
spawn() vs spawn_blocking()
spawn() | spawn_blocking() | |
---|---|---|
What | spawn Non-blocking tasks within tokio runtime | spawn blocking tasks within tokio runtime |
Where task is executed | Within the Tokio runtime's event loop | In separate thread from the Tokio runtime's thread pool |
blocking | no | Yes. Perform CPU-bound or blocking operations without blocking the Tokio runtime's event loop |
spawn() vs spawn_local()
spawn() | spawn_local() | |
---|---|---|
What | spawns async task | same |
Where task is executed | Spwaned Task can run on any thread managed by Tokio | Task should run on same thread that called tokio::spawn_local() |
block_on() vs spawn_blocking()
block_on() | spawn_blocking() | |
---|---|---|
What |
Run 1 future to completion and there is only thread within tokio - There are no other tasks on tokio |
This spawn a blocking task into a separate thread from the Tokio runtime's thread pool. while there can be other non-blocking tasks on tokio runtime |