Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

multithreading - Rust handling variable outside the scoped_threshhold

from rust beginner.

I have some problems about ownership I think. What i wanna do is changing "ret" which is boolean type variable inside the pool block. But when i ran the code and checked the ret, it changed well inside the pool block but outside the block, ret alway behave as true,,, plz fix my headache...

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 */ }
question from:https://stackoverflow.com/questions/65916854/rust-handling-variable-outside-the-scoped-threshhold

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

scoped_threadpool::Pool::scoped(&mut self, <closure>) returns a closure that impls FnOnce which means you can only call it once. You had it inside a for loop which is why the compiler kept giving you errors with confusing suggestions. Once you refactor the code to move the for outside the call to scoped then it compiles and works as expected:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...