Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 21, 2018 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/3cb9e060499e394843d3a3631ff76dec to your computer and use it in GitHub Desktop.
Save rust-play/3cb9e060499e394843d3a3631ff76dec to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::fs::File;
use std::io::prelude::*;
use std::thread;
use std::sync::Arc;
extern crate regex;
use regex::Regex;
const NUMBER_OF_THREADS: usize = 5;
struct ThreadData {
vector_of_strings: Vec<String>,
terms: Vec<& 'static str>,
quotient: usize
}
fn main()
{
let mut file = File::open("info2.txt").expect("Can't open file!");
let mut terms: Vec<&str> = Vec::new();
construct_regex(&mut terms);
let mut contents = String::new();
file.read_to_string(&mut contents) //TODO: Uhhh... This should prob be a memory map at some point
.expect("Oops! Can not read the file...");
let vector_of_strings: Vec<String> = contents.split("\n").map(|s| s.to_string()).collect();
let total_lines: usize = vector_of_strings.len();
println!("Total # of lines in file: {}", total_lines);
let quotient: usize = total_lines / NUMBER_OF_THREADS;
let td = ThreadData {
vector_of_strings: vector_of_strings,
terms: terms,
quotient
};
let td_arc = Arc::new(td);
threaded_search(td_arc);
println!("Done, exiting...");
}
fn threaded_search<'a>(td_arc: Arc<ThreadData>)
{
let new_tda1 = td_arc.clone();
let new_tda2 = td_arc.clone();
let new_tda3 = td_arc.clone();
let new_tda4 = td_arc.clone();
let new_tda5 = td_arc.clone();
let strings_as_slice1 = new_tda1.vector_of_strings.as_slice();
let strings_as_slice2 = new_tda2.vector_of_strings.as_slice();
let strings_as_slice3 = new_tda3.vector_of_strings.as_slice();
let strings_as_slice4 = new_tda4.vector_of_strings.as_slice();
let strings_as_slice5 = new_tda5.vector_of_strings.as_slice();
let handle1 = thread::spawn(move || {perform_search(&strings_as_slice1[0..new_tda1.quotient], &new_tda1.terms);});
let handle2 = thread::spawn(move || {perform_search(&strings_as_slice2[new_tda2.quotient..new_tda2.quotient*2], &new_tda2.terms);});
let handle3 = thread::spawn(move || {perform_search(&strings_as_slice3[new_tda2.quotient*2..new_tda2.quotient*3], &new_tda3.terms);});
let handle4 = thread::spawn(move || {perform_search(&strings_as_slice4[new_tda3.quotient*3..new_tda3.quotient*4], &new_tda4.terms);});
let handle5 = thread::spawn(move || {perform_search(&strings_as_slice5[new_tda4.quotient*4..new_tda4.quotient*5], &new_tda5.terms);});
handle1.join().unwrap();
handle2.join().unwrap();
handle3.join().unwrap();
handle4.join().unwrap();
handle5.join().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment