Stuck trying to pass closure between threads


#1

Been deadlocked with this all day, can’t really find the wiggle out. Probably because I have no idea why the errors come up

use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::thread;
use std::thread::JoinHandle;

struct Server {
    handler: Arc<Mutex<FnMut() -> () + Sync + Send + 'static>>,
}

impl Server {
    fn on_message(&mut self) {
        let mut h = self.handler.clone();
        thread::spawn(move || {
            {
                //let mut handler = h.lock().unwrap();
                let mut handler = h.get_mut().unwrap();

                (handler)();
            }
        });
    }
}

#[test]
fn test_visualize_vad() {
    Server {
        handler: Arc::new(Mutex::new(|| {})),
    }
}

cannot borrow immutable borrowed content as mutable

Errors on let mut handler = h.get_mut().unwrap();

Or errors on (handler)(); if I go with the lock() commented out line. I tried let mut h = self.get_mut.unwrap(); on the Arc, but then I run into a slew of even scarier lifetime errors. I’m stuck.


#2

Need to use lock() and then mut deref it to get the closure mutably borrowed:

let handler = &mut *h.lock().unwrap();
handler();