These are chat archives for rust-lang/rust

16th
Jul 2017
RuRu92
@RuRu92
Jul 16 2017 10:26
How many times can I copy obj inside Arc?
    println!("Hello, world!");
    let holder = Arc::new(Container {numbers: Arc::new(Mutex::new(vec![]))});
//    let mut holder = Arc<Mutex<Container>>::new(Container {numbers: vec![]});
    let mut writer = Writer { name: "writer".to_string(), number: 1 };
    let mut reader = Reader::new("reader".to_string(), 1);

    let mut io = Arc::new((writer, reader));

    let _ = thread::spawn(move || {
        let container = holder.clone();
        for num in 0..20 {
            let io = io.0.clone();

            io.write(&container, num);
        };
    }).join();

    let _ = thread::spawn(move || {
        let container = holder.clone();

        for num in 0..20 {
            let io = io.1.clone();

            io.read(&container, num);
        };
    }).join();
Compiler is complaining about me passing holder to a new thread for reading
vberset
@vberset
Jul 16 2017 14:30
@RuRu92 Because you use holder inside the closure of the first thread, and that closure has a move semantic, holder is moved to it. So you can't use it anymore outside the first closure. You must do the let container = holder.clone(); earlier, out of the scope of the closure. Thus, container will be moved to the thread and holder will stay available and clonable.