Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. use std::thread;
  2.  
  3. // make trait alias
  4. trait SafeFnMut: FnMut() + Send + Sync {}
  5. impl<F> SafeFnMut for F where F: FnMut() + Send + Sync {}
  6.  
  7. #[derive(Clone, Debug)]
  8. struct WithCall<F> {
  9. fp: Box<F>,
  10. }
  11.  
  12. impl<F> WithCall<F>
  13. where
  14. F: SafeFnMut,
  15. {
  16. // boxing the closure here
  17. pub fn new(fp: F) -> Self {
  18. WithCall { fp: Box::new(fp) }
  19. }
  20.  
  21. pub fn run(&mut self) {
  22. (self.fp)()
  23. }
  24. }
  25.  
  26. struct HasWithCall<T, U>
  27. where
  28. T: SafeFnMut,
  29. U: SafeFnMut,
  30. {
  31. pub first_fn: Option<Box<WithCall<T>>>,
  32. pub second_fn: Option<Box<WithCall<U>>>,
  33. }
  34.  
  35. fn main() {
  36. let mut first_fn = WithCall::new(|| println!("Called!"));
  37.  
  38. let second_fn = WithCall::new(|| println!("Called other!"));
  39.  
  40. let has_with_call = HasWithCall {
  41. first_fn: Some(Box::new(first_fn.clone())),
  42. second_fn: Some(Box::new(second_fn.clone())),
  43. };
  44.  
  45. println!("{:?}", first_fn.run());
  46.  
  47. let mut first_fn_a = first_fn.clone();
  48. let mut first_fn_b = first_fn;
  49.  
  50. let a = thread::spawn(move || {
  51. println!("In remote thread: {:?}", first_fn_a.run());
  52. });
  53.  
  54. let b = thread::spawn(move || {
  55. println!("In remote thread: {:?}", first_fn_b.run());
  56. });
  57.  
  58. a.join().expect("Thread A panicked");
  59. b.join().expect("Thread B panicked");
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement