如何解决Rust 处理 scoped_threshhold 之外的变量
来自 Rust 初学者。
我认为在所有权方面存在一些问题。我想做的是改变布尔值的“ret” 池块内的类型变量。但是,当我运行代码并检查 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");
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。