Skip to content

Commit 208dd29

Browse files
Zoxccuviper
authored andcommitted
Add the ability to create scoped thread pools
1 parent 93d40b5 commit 208dd29

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

rayon-core/src/registry.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,6 @@ impl Registry {
352352

353353
/// Waits for the worker threads to stop. This is used for testing
354354
/// -- so we can check that termination actually works.
355-
#[cfg(test)]
356355
pub(super) fn wait_until_stopped(&self) {
357356
for info in &self.thread_infos {
358357
info.stopped.wait();

rayon-core/src/thread_pool/mod.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,43 @@ impl ThreadPool {
9292
&DEFAULT_THREAD_POOL
9393
}
9494

95+
/// Creates a scoped thread pool
96+
pub fn scoped_pool<F, R, H>(
97+
builder: ThreadPoolBuilder,
98+
main_handler: H,
99+
with_pool: F,
100+
) -> Result<R, ThreadPoolBuildError>
101+
where
102+
F: FnOnce(&ThreadPool) -> R,
103+
H: Fn(&mut FnMut()) + Send + Sync,
104+
{
105+
struct Handler(*const ());
106+
unsafe impl Send for Handler {}
107+
unsafe impl Sync for Handler {}
108+
109+
let handler = Handler(&main_handler as *const _ as *const ());
110+
111+
let builder = builder.main_handler(move |_, worker| {
112+
let handler = unsafe { &*(handler.0 as *const H) };
113+
handler(worker);
114+
});
115+
116+
let pool = builder.build()?;
117+
118+
struct JoinRegistry(Arc<Registry>);
119+
120+
impl Drop for JoinRegistry {
121+
fn drop(&mut self) {
122+
self.0.terminate();
123+
self.0.wait_until_stopped();
124+
}
125+
}
126+
127+
let _join_registry = JoinRegistry(pool.registry.clone());
128+
129+
Ok(with_pool(&pool))
130+
}
131+
95132
/// Executes `op` within the threadpool. Any attempts to use
96133
/// `join`, `scope`, or parallel iterators will then operate
97134
/// within that threadpool.

0 commit comments

Comments
 (0)