2020-12-31
Awaiting a task will block until it's complete.
In the following code: x
is first completed, then y
let x = some_task().await;
let y = some_other_task().await;
To create a runtime use
async some_task() -> u32 {
123
}
let runtime = tokio::runtime::Runtime::new().unwrap();
let value = runtime.block_on(some_task());
join
spawn
can be considered analogous to std::thread::spawn
.
Spawning a task returns a Future
(that can be await
ed).
There is no guarantee that a spawn
ed tasks ends up on the same
thread as another spawn
ed task (unless it's on a single threaded runtime)
join!
is local which means tasks that are !Send
are possible.spawn(some_future())
is spawned into a task pool.async get_number() -> u32 {
5
}
async no_spawn() -> *const () {
&()
}
async fn use_join() -> u32 {
// join three futures
let (a, b, c) = tokio::join!(get_number(), get_number(), no_spawn());
a + b
}
For reading / writing use tokio::io::{AsyncReadExt, AsyncWriteExt}
.
async fn handle_socket(mut s: TcpStream) -> io::Result<()> {
let mut buf = [0u8; 64];
let res = s.read(&mut buf).await?;
s.write(&buf[..res]).await?;
Ok(())
}