1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use crossbeam_utils::thread;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use std::sync::{Arc, Mutex, MutexGuard};
pub fn frequency_finder<T>(list: &[T], nthreads: usize) -> HashMap<T, u32>
where
    T: Copy + Hash + Eq + Sync + Send + Debug,
{
    let len: usize = list.len();
    let range: usize = len / nthreads;
    let split_index: usize = nthreads * range;
    let residue: usize = len % nthreads;
    
    let map: Arc<Mutex<HashMap<T, u32>>> = Arc::new(Mutex::new(HashMap::new()));
    thread::scope(|s| {
        for i in 1..=nthreads {
            let map_arc: Arc<Mutex<HashMap<T, u32>>> = Arc::clone(&map);
            s.spawn(move |_| {
                let mut map_guard: MutexGuard<HashMap<T, u32>> = map_arc.lock().unwrap();
                for k in (i - 1) * range..i * range {
                    match map_guard.get_mut(&list[k]) {
                        Some(val) => {
                            *val += 1;
                        }
                        None => {
                            map_guard.insert(list[k], 1);
                        }
                    }
                }
            });
        }
    })
    .unwrap();
    let mut map: HashMap<T, u32> = Arc::try_unwrap(map).unwrap().into_inner().unwrap();
    
    for k in split_index..split_index + residue {
        match map.get_mut(&list[k]) {
            Some(val) => {
                *val += 1;
            }
            None => {
                map.insert(list[k], 1);
            }
        }
    }
    map
}