Search code examples
multithreadingrustwaitnotify

How to freeze a thread and notify it from another?


I need to pause the current thread in Rust and notify it from another thread. In Java I would write:

synchronized(myThread) {
    myThread.wait();
}

and from the second thread (to resume main thread):

synchronized(myThread){
    myThread.notify();
}

Is is possible to do the same in Rust?


Solution

  • Using a channel that sends type () is probably easiest:

    use std::sync::mpsc::channel;
    use std::thread;
    
    let (tx,rx) = channel();
    
    // Spawn your worker thread, giving it `send` and whatever else it needs
    thread::spawn(move|| {
        // Do whatever
        tx.send(()).expect("Could not send signal on channel.");
        // Continue
    });
    
    // Do whatever
    rx.recv().expect("Could not receive from channel.");
    // Continue working
    

    The () type is because it's effectively zero-information, which means it's pretty clear you're only using it as a signal. The fact that it's size zero means it's also potentially faster in some scenarios (but realistically probably not any faster than a normal machine word write).

    If you just need to notify the program that a thread is done, you can grab its join guard and wait for it to join.

    let guard = thread::spawn( ... ); // This will automatically join when finished computing
    
    guard.join().expect("Could not join thread");