<MUTEX>.lock() not keep lock in his scope. Why doesn't Err?

I'm trying to break the code.
I don't know why I get Ok (..) instead of Err (..)

let p = m1_clone.try_lock();  # I should get Err (..), it always gets Ok (..)

because:

println!("m1: {}", *m1.lock().unwrap());
std::thread::sleep(std::time::Duration::from_secs(20)); # Holds lock for 20 sec.

"mutexes are unlocked automatically, when a guard goes out of scope" but - but i'm in the scope for 20 sec

Output:

hi from MAIN !
m1: 100
Some("slowwly_3000"): http://www.google.co.uk/
Ok(100)
Some("slowwly_3000"): http://www.google.co.uk/
Ok(101)
Some("slowwly_3000"): http://www.google.co.uk/
...

CODE:

pub fn test_3() {
    let m1 = Arc::new(Mutex::new(100));
    let m1_clone = Arc::clone(&m1);

    std::thread::Builder::new().name("slowwly_3000".to_string()).spawn(move || {
        loop {
            let mut request = ureq::get("http://slowwly.robertomurray.co.uk/delay/3000/url/http://www.google.co.uk");
            let resp = request.call();
            println!("{:?}: {}", std::thread::current().name(), resp.get_url());
            let p = m1_clone.try_lock();
            println!("{:?}", p);
            let mut num = p.unwrap();
            *num += 1;
        }
    }).unwrap();

    loop {
        std::thread::sleep(std::time::Duration::from_secs(1));
        println!("hi from MAIN !");
        println!("m1: {}", *m1.lock().unwrap());
        std::thread::sleep(std::time::Duration::from_secs(20));
    }
}

The lock function returns a guard that will unlock the mutex when it's dropped. Since you're not storing the guard anywhere, it's dropped immediately and the mutex is unlocked immediately.

4 Likes

By "dropped immediately" you mean - "MutexGuard" is dropped at the end of this statement?

Yes.