Last active
February 24, 2022 05:31
-
-
Save dongnguyenltqb/59051d8b31ec5176cf1f4a6b90cc5a11 to your computer and use it in GitHub Desktop.
rust-wokers.rs
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 std::{ | |
sync::{ | |
mpsc::{channel, Receiver, Sender}, | |
Arc, Mutex, | |
}, | |
thread, | |
time::Duration, | |
}; | |
#[derive(Debug)] | |
struct Worker<T> | |
where | |
T: Send, | |
{ | |
tx: Sender<T>, | |
rx: Arc<Mutex<Receiver<T>>>, | |
} | |
impl<T> Worker<T> | |
where | |
T: Send + 'static, | |
{ | |
fn new() -> Worker<T> { | |
let (tx, rx) = channel::<T>(); | |
Worker { | |
tx, | |
rx: Arc::new(Mutex::new(rx)), | |
} | |
} | |
fn handle(&self, f: fn(job: T)) { | |
let rx = Arc::clone(&self.rx); | |
thread::spawn(move || { | |
println!("Listener is running."); | |
let rx = rx.lock().unwrap(); | |
while let Ok(j) = rx.recv() { | |
f(j); | |
} | |
}); | |
} | |
fn clone_sender(&self) -> Sender<T> { | |
self.tx.clone() | |
} | |
} | |
fn main() { | |
let w = Worker::<String>::new(); | |
let hand_fn = |s: String| { | |
thread::sleep(Duration::from_secs(2)); | |
println!("handling job {}", s); | |
}; | |
w.handle(hand_fn); | |
let mut count = 0; | |
let tx1 = w.clone_sender(); | |
let tx2 = w.clone_sender(); | |
thread::spawn(move || loop { | |
thread::sleep(Duration::from_secs(1)); | |
count += 1; | |
tx1.send(count.to_string() + " from thread 1"); | |
}); | |
loop { | |
count += 1; | |
thread::sleep(Duration::from_secs(1)); | |
tx2.send(count.to_string() + " from thread 2"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment