Execution Hangs if Mutex Lock Created in Main Thread Before Joins

Hi, I'm trying to understand why this code hangs

fn main(){
    let num = Arc::new(Mutex::new(0_u32));
    let num2 = num.clone();

    let h = thread::spawn(move || {
        thread::sleep(Duration::from_millis(1000));
        let mut num2_lock = num2.lock().unwrap();
        *num2_lock = 10_u32;
    } );

    let num_lock = num.lock().unwrap(); // <-- hangs if uncommented

    h.join().unwrap();

    //let num_lock = num.lock().unwrap(); // <-- does not hang 

    println!("{}", *num_lock);
}

If I create num_lock before the join() then it hangs. There is no compile time error. Just that run hangs as far as I can tell.

But if I create num_lock after the join(), the output is the value that I had set in the thread. Which is what I expected.

Can anyone please help me understand why the first version would hang?
Thanks,

It is because the Mutex stays locked while you call join, but the other thread is waiting for the main thread to release the lock.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.