Consecutively run a list/queue of async tasks

⚓ Rust    📅 2025-07-24    👤 surdeus    👁️ 1      

surdeus

Hi there,

To preface: I usually work in embedded C, and a little C++ so learning rust is quite a nice exercise! And I am learning about async functions by coding a program for a Artifacts MMO bot. I am having a lot of fun but am also a little lost.

I am trying to do a list of reqwest post/api calls (which are all async functions) and handle the result data one after the other.
For this I created a struct Player which will be updated by data received from these reqwest calls.

I am now using tokio::spawn to have two threads, which each handle their own data/player struct.
They will never have to share data but will have to run at the same time.

    let mut player1 = Player::new("NAME1");
    let mut player2 = Player::new("NAME2");

    if !player1.init_player().await {
        return;
    }
    if !player2.init_player().await {
        return;
    }
    
    let handler1 = 
        tokio::spawn(handle_1(player1));
    let handler2 = 
        tokio::spawn(handle_2(player2));

And the handle functions is something like

async fn handle_1(mut player: Player) {
    let player_mutex = Arc::new(Mutex::new(player));
   do_and_handle_api_call1(player_mutex.clone(), some_data).await;
   do_and_handle_api_call2(player_mutex.clone(), some_data).await;
}

This is working fine for now. But I would like to edit my code to have to list/vector/queue for each Player struct I can add these calls/tasks to.
And then have the program wait until there are tasks to execute, do them and go back to sleep and wait until new tasks are added. For this I have found std::sync::Condvar but I am not sure I am going in the right direction.

For context: Later I will use a gui/CLI (like ratatui or egui or a simple CLI) to add tasks to this queue but for now it is fine to add them all in one go in the main.

So now my question:
Could someone help me get into the right direction with code examples or reading material for managing this kind of queue?
Should I use a vector, FuturesOrdered or mpsc?

Is there some kind of crate for this? I am reading a lot about tokio async and futures and async/atomics but getting a bit overwhelmed and could use some directions on where to go and what route to take.

1 post - 1 participant

Read full topic

🏷️ Rust_feed