-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
while let doesn't work as expected with mutex #78390
Comments
This is an infinite loop, not a Rust compiler bug. fn main() {
let mut lock = vec![1; 10];
while let Some(x) = lock.pop() {
lock.push(x);
println!("the lock works as expected");
}
} |
It still doesn't work as expected: use std::sync::Mutex;
fn main() {
let lock = Mutex::new(vec![1; 1]);
while let Some(x) = lock.lock().unwrap().pop() {
if x != 1 {
break;
}
lock.lock().unwrap().push(x + 1);
println!("the lock works as expected");
}
} |
And, please pay attation to the backtrace in the issue description, it's a dead lock exactly. |
Yeah, but still it is a programming bug rather than a compiler bug. Rust makes no promise about deadlock.
Quoting the doc:
The working code is: use std::sync::Mutex;
fn main() {
let lock = Mutex::new(vec![1; 10]);
let mut inner = lock.lock().unwrap();
while let Some(x) = inner.pop() {
if x != 1 {
break;
}
inner.push(x + 1);
println!("the lock works as expected");
}
} |
You could also use |
Temporaries created in a |
I can understand this but my question is expression is different from while let Some(value) = value { /* some code */ } the value's lifetime should be equal to the whole loop. However Maybe it's hard to fix, but at least a clippy warning is helpful. |
In Rust, we call them place expressions or value expressions.
|
@lzutao I got it. I didn't know |
I tried this code:
I expected to see this happen: It can print the message, which means lock it again successfully
Instead, this happened: Nothing is print, which means dead lock
Meta
rustc --version --verbose
:Backtrace
The text was updated successfully, but these errors were encountered: