Sharing variable among threads safely


#1

I’d like to share the storage variable in the code below among threads. But obviously the code has a problem that it tries to move storage multiple times (because of the loop) and if I removed the move then storage becomes short lived and code won’t compile too.

Is there a safe way to achieve this?

use std::thread;
use std::sync::{Arc, Mutex};
use std::fs::File;
use std::io::prelude::*;

struct Storage {
    handler: File,
}

fn main() {
    let storage = Storage {
        handler: File::open("foo.txt").unwrap(),
    };

    let storage = Arc::new(storage);

    for _ in 0..30 {
        let handle = thread::spawn(move || {
            let stor = Arc::clone(&storage);
        });
    }
}

#2

The problem is that you move the only handle to the Arc in and then clone it. You want to clone it on each iteration of the loop and then move the clone into the thread.

    let storage = Arc::new(storage);

    for _ in 0..30 {
        let cloned_storage = Arc::clone(&storage);
        let handle = thread::spawn(move || {
            let local_storage  = cloned_storage;
        });
    }

(Go on, and you’ll find the place where you need the Mutex, but that’s fine :).