Usage of futures in Rust

Hi,

I already worked with coroutines in various other languages, mostly Kotlin & Go.
Now I'm practising rust and wanted to use rust's futures-library (0.3.5) for similar purposes.

Probably I'm using it wrong, but I'm not able to use rust's async-await mechanism the way I'm familar with.

An example case:
I have a Vec of futures, each doing a network request. Now I want to perform all of them in parallel. But the only wa to "execute" these function is to .await them one by one.
I actually don't see any difference to performing all requests synchronously.

Is there a way to "dispatch" the execution of async functions in parallel similar to the mechanism used in Go?

What's wrong with join_all?

As @Cerberuser mentioned you can use something like join_all or FuturesUnordered. And if you just want to "fire off" a task you can use some executor specific spawn method like tokio::spawn.

Thanks for your answers. I tried using join_all!(vec).await, but this resulted in an one-by-one execution of each vec-element syncronously.

e.g. following code:

async fn do_stuff(n: i32) {
    sleep(Duration::from_millis(1000));
    println!("{} done", n);
}

async fn work() {
    // create vec of 'do_stuff()'-futures
    join_all!(vec).await;
}

fn main() {
    block_on(work());
}

This code prints "n done" each second and is finished after vec.len() seconds.
My expactation would be that all futures print "at once" and the program execution is finished after roughly one second.

This is simulating a CPU-intensive calculation by tying up the current thread and preventing it from doing anything else. For that sort of workload, regular threading is the preferred method in Rust— async and futures are optimized for waiting on I/O operations.

2 Likes

And to add to @2e71828, if you just had sleep in there for the sake of example, you could try replacing it with (If you’re using tokio)

tokio::time::delay_for(Duration::from_millis(1000)).await
2 Likes

Note that this AFAIK wouldn't work at least in Kotlin, too: you can't Thread.sleep() in coroutine and have other coroutines executing at that time, you have to use special delay() function (which is itself async, or, in Kotlin terms, suspendable).

1 Like

Yes, you are right of course, my bad I totally forgot that this is blocking the whole thread :man_facepalming:

Now I got a better understanding of how it works in rust, thank you all :slight_smile:

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.