1

I have two threads that both need immutable access to a Vec and at the moment I'm having to make clone of that vector so both threads can use the data, I want to try and get rid of this extra copy

use clap::{App, Arg};
use std::fs;
use std::thread;

mod part1;
mod part2;

fn main() {
    let matches = App::new("day1")
        .about("AoC2018 day1")
        .arg(
            Arg::with_name("INPUT")
                .help("The file to read input from")
                .required(true)
                .index(1),
        )
        .get_matches();

    let filename = matches.value_of("INPUT").unwrap();
    let file_content = fs::read_to_string(filename).expect("Could not read/open file");

    let numbers: Vec<i64> = file_content
        .lines()
        .map(|x| x.parse::<i64>().expect("Could not extract value"))
        .collect();
    let numbers2 = numbers.clone();

    let handle1 = thread::spawn(move || part1::part1(&numbers));

    let handle2 = thread::spawn(move || part2::part2(&numbers2));

    let result1 = handle1.join();
    let result2 = handle2.join();

    println!("Part 1: {}", result1.unwrap());
    println!("Part 2: {}", result2.unwrap());
}

txk2048
  • 281
  • 3
  • 15
  • See also [Is it possible to share data with threads without any cloning?](https://stackoverflow.com/q/30795600/155423). You could put your `Vec` in an `Arc`, which makes the clone very cheap. – Shepmaster Aug 19 '19 at 19:51

0 Answers0