Hi, actually I had already used tokio for quite a while, but today I try to add a branch into tokio::select!
and I still confused about this details. For example let's see below 2 examples:
For the 1st example:
// Example-1
#[tokio::main]
async fn main() {
tokio::select! {
res1 = async {
tokio::time::sleep(Duration::from_secs(20)).await;
}
res2 = asyc {
tokio::time::sleep(Duration::from_secs(10)).await;
}
}
}
For the 2nd example:
// Sample-2
async fn main() {
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(20)).await;
tx1.send(1).await;
});
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(10)).await;
tx2.send(2).await;
});
tokio::select! {
res1 = rx1.recv() {/* Do nothing */}
res2 = rx2.recv() {/* Do nothing */}
}
}
For the 1st example, I write 2 async branches inside tokio::select!
, these two tasks are very simple sleep
, which means they can be very slow and cost a lot of time.
For the 2nd example, I spawn these 2 tasks into two tokio threads, and send messages after they complete. Inside tokio::select!
, I wait for these messages received.
Here're my several questions:
- In application layer, is there any differences between them?
- Is the 1st example running the two branches at the same time (parallel)? Or I have to
spawn
them into two async tasks to let them run at the same time? - Or, the
tokio::select!
can only run 1 branch at a time, it only waits for multiple branches, and once there's 1 branch triggered, it runs the triggered branch?