EDIT - Got solution working with "Crossbeam"
My solution:
use crossbeam::thread;
fn analyze_string(contents: String) -> u64 {
let splitted_contents = contents.split("\n").collect::<Vec<&str>>();
thread::scope(|s| {
let oxygen_thread = s.spawn(|_| {
let mut oxygen = splitted_contents.clone();
let mut n = 0;
while oxygen.len() > 1 {
if oxygen.len() > 1 {
let (z, o) = get_ratings_of_bits(&oxygen, n);
if z > o {
oxygen.retain(create_predicate('0', n));
} else if o > z {
oxygen.retain(create_predicate('1', n));
} else if o == z {
oxygen.retain(create_predicate('1', n));
}
}
n += 1;
}
oxygen.get(0).unwrap().clone()
});
let co2_thread = s.spawn(|_| {
let mut co2 = splitted_contents.clone();
let mut n = 0;
while co2.len() > 1 {
if co2.len() > 1 {
let (z, o) = get_ratings_of_bits(&co2, n);
if z > o {
co2.retain(create_predicate('1', n));
} else if o > z {
co2.retain(create_predicate('0', n));
} else if o == z {
co2.retain(create_predicate('0', n));
}
}
n += 1;
}
co2.get(0).unwrap().clone()
});
let oxygen_decimal = isize::from_str_radix(oxygen_thread.join().unwrap(), 2).unwrap();
let co2_decimal = isize::from_str_radix(co2_thread.join().unwrap(), 2).unwrap();
(oxygen_decimal * co2_decimal).try_into().unwrap()
}).unwrap()
}
I have a function that looks like this:
fn create_threads_and_handle_data(inputs: String) {
let splitted_inputs = inputs.split("\n").collect::<Vec<&str>>();
}
I want to use my variable splitted_inputs
in two different threads (because I want to speed this up a bit). So I am creating a thread like this:
fn create_threads_and_handle_data(inputs: String) {
let splitted_inputs = inputs.split("\n").collect::<Vec<&str>>();
let thread1 = thread::spawn(move || {
let mut copied: Vec<&str> = splitted_inputs.clone();
// Some irrelevant handling the copied vector
return copied.get(1).unwrap().clone();
)};
let thread2 = thread::spawn(move || {
let mut copied: Vec<&str> = splitted_inputs.clone();
// Some irrelevant handling the copied vector
return copied.get(0).unwrap().clone();
)};
let thread1_value = thread1.join().unwrap();
let thread2_value = thread2.join().unwrap();
}
Now I am getting an error that says "contents" does not live long enough. borrowed value does not live long enough
How do I alter this code so I can use the argument in my threads?