Skip to content

Instantly share code, notes, and snippets.

@lbfalvy
Last active November 26, 2024 00:08
Show Gist options
  • Save lbfalvy/1ca6b201b482950538d88c9b7e9f010f to your computer and use it in GitHub Desktop.
Save lbfalvy/1ca6b201b482950538d88c9b7e9f010f to your computer and use it in GitHub Desktop.
Demo for parallel futures in Rust
use std::time::Duration;
use async_std::sync::Mutex;
struct Foo(pub u64);
impl Foo {
pub async fn bar(&mut self) {
let my_mutex = Mutex::new(self);
futures::future::join(
async {
for _ in 0..100 {
my_mutex.lock().await.0 += 1;
tokio::time::sleep(Duration::from_nanos(1)).await
}
},
async {
for _ in 0..100 {
my_mutex.lock().await.0 += 1;
tokio::time::sleep(Duration::from_nanos(1)).await
}
}
).await;
}
}
#[tokio::main]
async fn main() {
let mut foo = Foo(1);
foo.bar().await;
println!("Hello, {}!", foo.0);
}
@lbfalvy
Copy link
Author

lbfalvy commented Nov 26, 2024

udate: apparently if you use the join function rather than the join! macro rust-analyzer won't be effectively disabled inside the async blocks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment