Last active
November 26, 2024 00:08
-
-
Save lbfalvy/1ca6b201b482950538d88c9b7e9f010f to your computer and use it in GitHub Desktop.
Demo for parallel futures in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
udate: apparently if you use the join function rather than the join! macro rust-analyzer won't be effectively disabled inside the async blocks