Skip to content

Instantly share code, notes, and snippets.

@dongnguyenltqb
Last active February 24, 2022 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dongnguyenltqb/59051d8b31ec5176cf1f4a6b90cc5a11 to your computer and use it in GitHub Desktop.
Save dongnguyenltqb/59051d8b31ec5176cf1f4a6b90cc5a11 to your computer and use it in GitHub Desktop.
rust-wokers.rs
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