Skip to content

Commit 24631d6

Browse files
authored
Merge pull request #1 from nkanaev/threads
parallelise using threads
2 parents bf0a41d + 7eded95 commit 24631d6

1 file changed

Lines changed: 18 additions & 8 deletions

File tree

‎src/pangram_machine.rs‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,19 @@
11
use crate::profile::*;
2+
use std::sync::{Arc, Mutex};
3+
use std::thread;
24

3-
pub fn pangram_machine<F: FnMut([usize; 26])>(initial_constants: &[usize; 26], profiles: &[Profile; 51], mut on_solution: F) -> u64 {
5+
pub fn pangram_machine<F: FnMut([usize; 26]) + Send>(initial_constants: &[usize; 26], profiles: &[Profile; 51], on_solution: F) -> u64 {
46
let sumprofile = Profile::from(initial_constants);
5-
let mut num_iterations = 0;
7+
let on_solution = Arc::new(Mutex::new(on_solution));
68

79
// Iterate through every combination within the specified ranges.
8-
for e_counter in 25..=32 {
9-
let sumprofile = &sumprofile + &profiles[e_counter];
10+
let sumprofile = &sumprofile;
11+
thread::scope(|s| {
12+
let handles: Vec<_> = (25..=32).map(|e_counter| {
13+
let on_solution = Arc::clone(&on_solution);
14+
s.spawn(move || {
15+
let sumprofile = sumprofile + &profiles[e_counter];
16+
let mut num_iterations = 0u64;
1017
for f_counter in 4..=9 {
1118
let sumprofile = &sumprofile + &profiles[f_counter];
1219
for h_counter in 3..=8 {
@@ -66,10 +73,13 @@ pub fn pangram_machine<F: FnMut([usize; 26])>(initial_constants: &[usize; 26], p
6673
if v_counter as u8 != v { continue; }
6774
if w_counter as u8 != w { continue; }
6875

69-
on_solution(sumprofile.with(initial_constants));
70-
}}}}}}}}}}}}
71-
72-
num_iterations
76+
on_solution.lock().unwrap()(sumprofile.with(initial_constants));
77+
}}}}}}}}}}}
78+
num_iterations
79+
})
80+
}).collect();
81+
handles.into_iter().map(|h| h.join().unwrap()).sum()
82+
})
7383
}
7484

7585
#[cfg(test)]

0 commit comments

Comments
 (0)