How to join handles of threads

use std::sync::{Arc, Mutex};
use std::thread;
pub fn send_some_data(a: i64) {
    let mut int = 1;
    let arc = Arc::new(Mutex::new(int));
    let mut handles = vec![];
    for i in 0..a {
        let arc_clone = Arc::clone(&arc);
        let handle = thread::spawn(move ||
                let mut val= arc_clone.lock().unwrap();
                (*val) += 1;
    for handle in handles.iter()
        ^^^^^^ move occurs because `*handle` has type `std::thread::JoinHandle<()>`, which does not implement the `Copy` trait

Why? I mean, I can see that compiler is trying to explain, but none the less... If somebody could explain that to me in more digestible form. And how to fix that?

The root cause of the error is that you're trying to call a method that takes ownership while you only have a borrow. This is OK to do with types that implement Copy, but JoinHandle is not one of those.

Vec::iter returns an iterator of references. In this case, because you have a vec of JoinHandles, the type of handle in the loop is &JoinHandle, a borrow.

Looking at JoinHandle::join, we see that it takes ownership of the JoinHandle it is called with (because the argument is self and not &self or &mut self).

To fix this, you can simply drop the .iter() and the for loop will loop over owned JoinHandles instead.

1 Like

Ef me, fan-bloody-tastic!
Thanks man!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.