Created
November 16, 2024 16:05
-
-
Save abradley2/ab8d39e62e1d1d8b9b0b072444eab529 to your computer and use it in GitHub Desktop.
Integrating Tokio with synchronous code
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::{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