Skip to content

Instantly share code, notes, and snippets.

@abradley2
Created November 16, 2024 16:05
Show Gist options
  • Save abradley2/ab8d39e62e1d1d8b9b0b072444eab529 to your computer and use it in GitHub Desktop.
Save abradley2/ab8d39e62e1d1d8b9b0b072444eab529 to your computer and use it in GitHub Desktop.
Integrating Tokio with synchronous code
use std::{thread, time::Duration};
use tokio::{runtime::Builder, sync::mpsc};
fn main() {
let start_instant = std::time::Instant::now();
let runtime = Builder::new_multi_thread()
.worker_threads(3)
.enable_all()
.build()
.unwrap();
let done_1 = runtime.spawn(run());
let done_2 = runtime.spawn(run());
thread::sleep(Duration::new(2, 0));
let _ = runtime.block_on(done_1);
let _ = runtime.block_on(done_2);
let end_instant = std::time::Instant::now();
let execution_duration = end_instant - start_instant;
println!("Total duration: {}", execution_duration.as_secs());
}
async fn run() -> u32 {
let (tx, mut rx) = mpsc::channel(32);
let tx2 = tx.clone();
tokio::spawn(async move {
thread::sleep(Duration::new(1, 0));
tx.send(()).await.unwrap();
});
tokio::spawn(async move {
thread::sleep(Duration::new(2, 0));
tx2.send(()).await.unwrap();
});
let mut count = 0;
while count < 2 {
let _ = rx.recv().await;
count += 1;
}
count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment