Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::thread;
- // make trait alias
- trait SafeFnMut: FnMut() + Send + Sync {}
- impl<F> SafeFnMut for F where F: FnMut() + Send + Sync {}
- #[derive(Clone, Debug)]
- struct WithCall<F> {
- fp: Box<F>,
- }
- impl<F> WithCall<F>
- where
- F: SafeFnMut,
- {
- // boxing the closure here
- pub fn new(fp: F) -> Self {
- WithCall { fp: Box::new(fp) }
- }
- pub fn run(&mut self) {
- (self.fp)()
- }
- }
- struct HasWithCall<T, U>
- where
- T: SafeFnMut,
- U: SafeFnMut,
- {
- pub first_fn: Option<Box<WithCall<T>>>,
- pub second_fn: Option<Box<WithCall<U>>>,
- }
- fn main() {
- let mut first_fn = WithCall::new(|| println!("Called!"));
- let second_fn = WithCall::new(|| println!("Called other!"));
- let has_with_call = HasWithCall {
- first_fn: Some(Box::new(first_fn.clone())),
- second_fn: Some(Box::new(second_fn.clone())),
- };
- println!("{:?}", first_fn.run());
- let mut first_fn_a = first_fn.clone();
- let mut first_fn_b = first_fn;
- let a = thread::spawn(move || {
- println!("In remote thread: {:?}", first_fn_a.run());
- });
- let b = thread::spawn(move || {
- println!("In remote thread: {:?}", first_fn_b.run());
- });
- a.join().expect("Thread A panicked");
- b.join().expect("Thread B panicked");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement