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
379 views
in Technique[技术] by (71.8m points)

multithreading - Why does incrementing an integer in a thread not change the value outside of the thread?

I have this code:

fn main() {
    let mut total: i64 = 0;
    let pool = ThreadPool::with_name("search worker".to_owned(), num_cpus::get());
    let items = getItems(); // returns a vector of sorts
    let client = blocking::Client::new();
    for item in items {
        let t_client = client.clone(); // must clone here for some reason
        let mut took: i64 = 0;
        pool.execute(move || {
            took = worker(t_client);
            total += took;
        });
    }
    println!("{}", total);
}

fn worker(c: blocking::Client) -> i64 {
    // do some stuff and return a value
    // for sake of an example, return 25

    25
}

I had to use the move clause in the call to execute.

The problem is that the value of the total variable remains zero. It looks like it's being duplicated inside that loop and the local variable does not get modified at all.

I do get a warning on took = worker(t_client); and on total_took += took; which is that those variables aren't never read.

I ended up "solving" this by making that variable static and using unsafe, but that's not a solution. Also, eventually I need to get more results from that worker function and if I put a reference to a variable, it tell me that I can't borrow more than once, which I don't really understand.


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

1 Answer

0 votes
by (71.8m points)

total is of type i64 which implements the Copy trait so it's implicitly copied on moves. If you want to share some mutable value T across multiple threads you need to wrap it in an Arc<Mutex<T>> (Arc docs & Mutex docs), or in this particular case, since you're using an i64, you can use an AtomicI64 instead.


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

...