Can tokio::select! run multiple branches at the same time?

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:

  1. In application layer, is there any differences between them?
  2. 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?
  3. 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?

Both branches are executed concurrently, not parallelly, in your first example. They both will be polled by the main thread and not by a worker thread (if you have a multi-threaded runtime, which you do when annotating your main with #[tokio::main]). Only spawned tasks run on the worker threads.

The select! section of the tutorial is quite comprehensible.

2 Likes

thank you, got it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.