You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
use std::sync::Mutex;fnmain(){dead_lock_2();}fndead_lock_1(){let vec_mutex = Mutex::new(vec![1,2,3]);// It's known that the temporary MutexGuard will be dropped at the end of while let, and will cause a dead lock.whileletSome(num) = vec_mutex.lock().unwrap().pop(){if num == 2{
vec_mutex.lock().unwrap().push(4);}println!("got {}", num);}}fndead_lock_2(){let vec_mutex = Mutex::new(vec![1,2,3]);// I add a scope, and expect the temporary MutexGuard dropped at the end of the scope. It does not work as I expect.whileletSome(num) = {
vec_mutex.lock().unwrap().pop()}{if num == 2{
vec_mutex.lock().unwrap().push(4);}println!("got {}", num);}}fnno_dead_lock(){let vec_mutex = Mutex::new(vec![1,2,3]);// It works. whileletSome(num) = {let num = vec_mutex.lock().unwrap().pop();
num
}{if num == 2{
vec_mutex.lock().unwrap().push(4);}println!("got {}", num);}}
I expected to see this happen: the dead_lock_2 function got outputs as expect.
got 3
got 2
got 4
got 1
Instead, this happened: the dead_lock_2 function got deadlock unexpected.
I have got the answer: #37612 (comment)
The drop scope of the temporary is usually the end of the enclosing statement.
But a block expression is not a statement, so { vec_mutex.lock().unwrap().pop() } will not drop the temporary.
I have checked #21114 #37612 #60107 and #78390 .
I tried this code:
I expected to see this happen: the dead_lock_2 function got outputs as expect.
Instead, this happened: the dead_lock_2 function got deadlock unexpected.
Meta
rustc --version --verbose
:I have got the answer: #37612 (comment)
The drop scope of the temporary is usually the end of the enclosing statement.
But a block expression is not a statement, so
{ vec_mutex.lock().unwrap().pop() }
will not drop the temporary.It's a pitfall, so I think it should be:
The text was updated successfully, but these errors were encountered: