Guest User

Untitled

a guest
Apr 25th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. use std::sync::{Arc, Mutex};
  2. use std::thread;
  3.  
  4. enum Change<T> {
  5. Small(T),
  6. Large(T),
  7. }
  8.  
  9. struct ChangeEmitter<T> {
  10. listener: Arc<Mutex<Option<Box<Fn(Change<T>) + Send>>>>,
  11. }
  12.  
  13. impl<T: 'static + Send> ChangeEmitter<T> {
  14. pub fn new() -> Self {
  15. let emitter = ChangeEmitter::<T> {
  16. listener: Arc::new(Mutex::new(None)),
  17. };
  18.  
  19. emitter
  20. }
  21.  
  22. pub fn listen(&mut self, f: Box<Fn(Change<T>) + Send>) {
  23. let mut listener = self.listener.lock().unwrap();
  24. *listener = Some(f);
  25. }
  26.  
  27. pub fn run(&self, values: Vec<T>) -> thread::JoinHandle<()> {
  28. let thread_listener = self.listener.clone();
  29.  
  30. thread::spawn(move || {
  31. let locked = thread_listener.lock().unwrap();
  32.  
  33. match *locked {
  34. Some(ref f) => {
  35. for value in values {
  36. let change = Change::Small(value);
  37. f(change);
  38. }
  39. }
  40. None => {}
  41. }
  42. })
  43. }
  44. }
  45.  
  46. fn main() {
  47. let mut emitter = ChangeEmitter::<i32>::new();
  48.  
  49. // Listen to changes
  50. emitter.listen(Box::new(|change| match change {
  51. Change::Small(v) => println!("Small change: {}", v),
  52. Change::Large(v) => println!("Large change: {}", v),
  53. }));
  54.  
  55. emitter.run(vec![5i32, 10i32, 100i32]).join().expect("thread to run successfully");
  56. }
Add Comment
Please, Sign In to add comment