What's happening when i call stdin.lock() twice?

im just wondering what will happen if i call lock() twice
here's a function

fn a() {
    let a = stdin();
    let mut l = a.lock().lines();
    //this line would cause the problem
    // let mut lw = a.lock().lines();
    let n = l.next();
    dbg!(n);
    let nw = l.next();
    dbg!(nw);
    dbg!(l);
}

ok i found that anything i type into terminal will change nothing, whatever i put in will just do nothing.
what's happening?
please explain it for me, thx!

This will deadlock your program. Stdin is a Mutex in disguise and a StdinLock is a MutexGuard of the Mutex that underlies Stdin and wraps the raw stdin file descriptor. If you try to acquire a guard to a mutex on the same thread that is already holding a guard to the same mutex, trying to lock said mutex a second time will never complete, because your thread will wait for itself to release the mutex, which will never happen as your thread is currently busy waiting for the lock to become available.

6 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.