scoped_threshhold 之外的 Rust 处理变量

Rust handling variable outside the scoped_threshhold

来自 Rust 初学者。

我认为我对所有权有一些疑问。我想做的是改变布尔值“ret” 池块内的类型变量。但是当我 运行 代码并检查 ret 时,它在 pool 块内发生了很好的变化,但在块外,ret 始终表现为 true, 请解决我的头痛...

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>) returns a closure that impls 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");
    }
}

playground