Skip to content

Commit 10f7542

Browse files
committed
Collect values from joined threads
1 parent 5792f82 commit 10f7542

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

src/util/thread.rs

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,26 @@ use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
66
use std::thread::*;
77

88
/// Usually the number of physical cores.
9-
fn threads() -> usize {
9+
pub fn threads() -> usize {
1010
available_parallelism().unwrap().get()
1111
}
1212

1313
/// Spawn `n` scoped threads, where `n` is the available parallelism.
14-
pub fn spawn<F>(f: F)
14+
pub fn spawn<F, R>(f: F) -> Vec<R>
1515
where
16-
F: Fn() + Copy + Send,
16+
F: Fn() -> R + Copy + Send,
17+
R: Send,
1718
{
1819
scope(|scope| {
20+
let mut handles = Vec::new();
21+
1922
for _ in 0..threads() {
20-
scope.spawn(f);
23+
let handle = scope.spawn(f);
24+
handles.push(handle);
2125
}
22-
});
26+
27+
handles.into_iter().flat_map(ScopedJoinHandle::join).collect()
28+
})
2329
}
2430

2531
/// Spawns `n` scoped threads that each receive a
@@ -28,9 +34,10 @@ where
2834
/// than other to process, used by popular libraries such as [rayon](https://github.com/rayon-rs/rayon).
2935
/// Processing at different rates also happens on many modern CPUs with
3036
/// [heterogeneous performance and efficiency cores](https://en.wikipedia.org/wiki/ARM_big.LITTLE).
31-
pub fn spawn_parallel_iterator<F, T>(items: &[T], f: F)
37+
pub fn spawn_parallel_iterator<F, R, T>(items: &[T], f: F) -> Vec<R>
3238
where
33-
F: Fn(ParIter<'_, T>) + Copy + Send,
39+
F: Fn(ParIter<'_, T>) -> R + Copy + Send,
40+
R: Send,
3441
T: Sync,
3542
{
3643
let threads = threads();
@@ -47,10 +54,15 @@ where
4754
let workers = workers.as_slice();
4855

4956
scope(|scope| {
57+
let mut handles = Vec::new();
58+
5059
for id in 0..threads {
51-
scope.spawn(move || f(ParIter { id, items, workers }));
60+
let handle = scope.spawn(move || f(ParIter { id, items, workers }));
61+
handles.push(handle);
5262
}
53-
});
63+
64+
handles.into_iter().flat_map(ScopedJoinHandle::join).collect()
65+
})
5466
}
5567

5668
pub struct ParIter<'a, T> {

0 commit comments

Comments
 (0)