Last active
May 6, 2021 07:50
-
-
Save CarlosLanderas/25b4105f7765ac4baac8213d22fc0722 to your computer and use it in GitHub Desktop.
Rust channel threads with cancellation sample
This file contains 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 anyhow::Result; | |
use std::sync::Arc; | |
use std::time::Duration; | |
#[tokio::main] | |
async fn main() -> Result<()> { | |
let (tx, rx) = std::sync::mpsc::channel(); | |
let cts = Arc::new(cancellation::CancellationTokenSource::new()); | |
let cts_clone = cts.clone(); | |
let t1 = tokio::spawn(async move { | |
let mut counter: u64 = 1; | |
while !cts_clone.is_canceled() { | |
tx.send(format!("Sending message {} to channel", counter)).unwrap(); | |
counter += 1; | |
tokio::time::sleep(Duration::from_millis(2000)).await; | |
} | |
drop(tx); | |
println!("Dropping writing channel due to cancellation"); | |
}); | |
let t2 = tokio::spawn(async move { | |
while let Ok(message) = rx.recv() { | |
println!("Received message: {}", message); | |
} | |
println!("Existing reader thread. Channel closed"); | |
}); | |
ctrlc::set_handler(move || { | |
println!("Cancelling"); | |
cts.cancel(); | |
})?; | |
let _ = tokio::join!(t1, t2); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment