from rust初学者。
我认为我有一些关于所有权的问题。我想做的是改变"这是布尔值在池块内键入变量。但是当我运行代码并检查ret时,它在池块内改变得很好,但在块外,ret总是表现为真…let mut pool = Pool::new(max_worker);
let mut ret = true;
pool.scoped(|scoped| {
for i in 0..somevalue{
scoped.execute( move || {
let ret_ref = &mut ret;
// Do Something
if success {
*ret_ref = false
}
});
}
});
if ret == true { /* Do Something */ }
scoped_threadpool::Pool::scoped(&mut self, <closure>)
返回一个包含FnOnce
的闭包,这意味着您只能调用它一次。你有它在一个for
循环,这就是为什么编译器不断给你的错误与令人困惑的建议。一旦您重构代码,将for
移出scoped
调用,那么它就会编译并按预期工作:
use scoped_threadpool::Pool;
fn main() {
let max_workers = 1;
let somevalue = 1;
let mut pool = Pool::new(max_workers);
let mut ret = true;
let ret_ref = &mut ret;
for i in 0..somevalue {
pool.scoped(|scoped| {
scoped.execute(|| {
// do something
let success = true;
if success {
*ret_ref = false
}
});
});
}
if ret == true {
println!("ret stayed true");
} else {
// prints this
println!("ret was changed to false in the scoped thread");
}
}
游乐场