-
-
Save szagi3891/328e2bdb180dc9899af8 to your computer and use it in GitHub Desktop.
podnoszenie wątków
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::sync::mpsc::{channel, Sender}; | |
use std::thread; | |
use std::time::Duration; | |
struct watch { | |
name : String, | |
chan: Sender<String>, | |
} | |
impl watch { | |
fn new(name: String, chan: Sender<String>) -> watch { | |
watch{name : name, chan: chan} | |
} | |
} | |
impl Drop for watch { | |
fn drop(&mut self) { | |
println!("koniec wątka {}", &self.name); | |
self.chan.send(self.name.clone()); | |
} | |
} | |
fn run_worker1(name: String, tx: Sender<String>) { | |
thread::spawn(move || { | |
let wat = watch::new(name, tx); | |
//jakiś kod workera | |
println!("1 usypia"); | |
thread::sleep(Duration::new(3, 0)); | |
println!("1 pobudka"); | |
panic!("panic1"); | |
}); | |
} | |
fn run_worker2(name: String, tx: Sender<String>) { | |
thread::spawn(move || { | |
let wat = watch::new(name, tx); | |
println!("2 usypia"); | |
thread::sleep(Duration::new(10, 0)); | |
println!("2 pobudka"); | |
panic!("panic2"); | |
}); | |
} | |
pub fn test() { | |
let (tx, rx) = channel(); | |
run_worker1("watek_pierwszy".to_string(), tx.clone()); | |
run_worker2("watek_drugi".to_string(), tx.clone()); | |
//od razu poeksperymentować z łapaniem sygnału ctrl+c - który posłuży do łagodnego wyjścia z programu | |
loop { | |
match rx.recv() { | |
Ok(thread_id) => { | |
if thread_id == "watek_pierwszy".to_string() { | |
run_worker1("watek_pierwszy".to_string(), tx.clone()); | |
} else if thread_id == "watek_drugi".to_string() { | |
run_worker2("watek_drugi".to_string(), tx.clone()); | |
} else { | |
panic!("nieprawidłowy identyfikator wątka"); | |
} | |
//println!("otrzymałem informację że umarł wątek: {:?}", rx.recv()); | |
} | |
Err(err) => { | |
panic!("panik w przechwytywaniu z kanału {:?}"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment