multithreading - 除scoped_threshhold外的Rust处理变量

标签 multithreading rust threadpool ownership

从 rust 初学者。
我认为所有权方面存在一些问题。我想做的是更改 bool 值的“ret”
池块中的type变量。但是,当我运行代码并检查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>) 返回一个表示 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

关于multithreading - 除scoped_threshhold外的Rust处理变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65916854/

相关文章:

rust - Diesel 可以在运行时更改模式吗?

multithreading - 斯卡拉的 Actor 池

java - 线程池不调整大小

c# - SemaphoreSlim(1) 如何知道是否有其他线程在等待

java - Java中什么情况下需要同步数组?

c# - 如何在命令启动后更改 sql 超时

rust - 使用借用作为关联的特征类型

Java:使用 ExecutorService 实现并发

error-handling - Rust 是否有提前返回错误的钩子(Hook)?

Groovy GPars,启动的每个线程都需要索引