Last active
October 17, 2022 05:42
-
-
Save chiro-hiro/81a4730d8e9d68a22165f69c46daf01e to your computer and use it in GitHub Desktop.
Example data sharing and channel
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 crossbeam::scope; | |
use crossbeam_channel::{select, unbounded}; | |
use env_logger::{Builder, Env}; | |
use log::info; | |
use std::sync::{Arc, Mutex}; | |
use std::thread; | |
use std::time::Duration; | |
fn main() { | |
Builder::from_env(Env::default().default_filter_or("info")).init(); | |
let (s, r) = unbounded(); | |
let counter = Arc::new(Mutex::new(0)); | |
scope(|scope| { | |
for i in 0..5 { | |
let (counter, sender) = (Arc::clone(&counter), s.clone()); | |
scope.spawn(move |_| { | |
let mut counter = counter.lock().unwrap(); | |
*counter += 1; | |
let result = format!("Hello bitch: {} from thread: {}", *counter, i); | |
info!("Send from: {}", result); | |
sender.send(String::from(result)).unwrap(); | |
thread::sleep(Duration::from_secs(1)) | |
}); | |
} | |
scope.spawn(move |_| loop { | |
select! { | |
recv(r) -> msg => { | |
info!("Received: {:?}", msg.unwrap()) | |
} | |
} | |
}); | |
}) | |
.unwrap(); | |
} |
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 env_logger::{Builder, Env}; | |
use log::info; | |
use std::sync::{Arc, Mutex}; | |
use std::thread; | |
use std::time::Duration; | |
use tokio::sync::mpsc::unbounded_channel; | |
use tokio::task::JoinHandle; | |
#[tokio::main] | |
async fn main() { | |
Builder::from_env(Env::default().default_filter_or("info")).init(); | |
let (s, mut r) = unbounded_channel::<String>(); | |
let counter = Arc::new(Mutex::new(0)); | |
let mut handlers = Vec::<JoinHandle<()>>::new(); | |
handlers.push(tokio::spawn(async move { | |
while let Some(data) = r.recv().await { | |
info!("Received: {:?}", data); | |
} | |
})); | |
for i in 1..6 { | |
let (counter, sender) = (Arc::clone(&counter), s.clone()); | |
handlers.push(tokio::spawn(async move { | |
let mut counter = counter.lock().unwrap(); | |
*counter += 1; | |
let result = format!("Hello bitch: {} from thread: {}", *counter, i); | |
info!("Send from: {}", result); | |
sender.send(String::from(result)).unwrap(); | |
thread::sleep(Duration::from_secs(1)) | |
})); | |
} | |
for i in 0..handlers.len() { | |
(&mut handlers[i]).await.unwrap(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment