使用互斥锁的 while 循环参数的生命周期是多少?
What are the lifetimes of while loop arguments using a mutex?
我正在研究 Rust 的 rustlings 练习,并为 threads1.rs
提出了一个解决方案,如下所示:
struct JobStatus {
jobs_completed: u32,
}
fn main() {
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = status.clone();
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
status_shared.lock().unwrap().jobs_completed += 1;
}
});
// WHILE LOOP IN QUESTION //
while status.lock().unwrap().jobs_completed < 10 {
println!("waiting... ");
thread::sleep(Duration::from_millis(500));
}
}
上述解决方案完美运行并给出了预期的结果(即主线程只需等待 6 次,派生线程即可完成 10 次迭代)。
但是,根据 Rust 的文档,Mutex 的锁仅在特定锁超出范围时才会释放。但我不明白为什么在 while 循环中创建的锁没有在整个迭代过程中保持,从而使主线程等待 10 次以上。是不是因为 jobs_completed
是一个固定大小的变量,在我们借用值时被复制到堆栈上,从而立即释放锁?还是 while 循环立即释放锁的其他原因?
Is it because jobs_completed is a fixed size variable and is copied onto the stack when we borrow the value and thereby immediately releasing the lock?
正在释放锁,因为锁守卫仅在访问 jobs_completed
时使用,因此锁仅在 while
的 条件.
如果“固定大小变量”是指 Sized
那么...不。 jobs_completed
是 Copy
让事情变得更简单,但即使它不是,锁仍然只 需要 在循环条件的范围内保持,所以如果不明确持有它,它仍然不会在整个循环中持有。
我正在研究 Rust 的 rustlings 练习,并为 threads1.rs
提出了一个解决方案,如下所示:
struct JobStatus {
jobs_completed: u32,
}
fn main() {
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let status_shared = status.clone();
thread::spawn(move || {
for _ in 0..10 {
thread::sleep(Duration::from_millis(250));
status_shared.lock().unwrap().jobs_completed += 1;
}
});
// WHILE LOOP IN QUESTION //
while status.lock().unwrap().jobs_completed < 10 {
println!("waiting... ");
thread::sleep(Duration::from_millis(500));
}
}
上述解决方案完美运行并给出了预期的结果(即主线程只需等待 6 次,派生线程即可完成 10 次迭代)。
但是,根据 Rust 的文档,Mutex 的锁仅在特定锁超出范围时才会释放。但我不明白为什么在 while 循环中创建的锁没有在整个迭代过程中保持,从而使主线程等待 10 次以上。是不是因为 jobs_completed
是一个固定大小的变量,在我们借用值时被复制到堆栈上,从而立即释放锁?还是 while 循环立即释放锁的其他原因?
Is it because jobs_completed is a fixed size variable and is copied onto the stack when we borrow the value and thereby immediately releasing the lock?
正在释放锁,因为锁守卫仅在访问 jobs_completed
时使用,因此锁仅在 while
的 条件.
如果“固定大小变量”是指 Sized
那么...不。 jobs_completed
是 Copy
让事情变得更简单,但即使它不是,锁仍然只 需要 在循环条件的范围内保持,所以如果不明确持有它,它仍然不会在整个循环中持有。