Skip to content

Commit

Permalink
Add the ability to create scoped thread pools
Browse files Browse the repository at this point in the history
  • Loading branch information
Zoxc committed Jan 31, 2019
1 parent e58b9c3 commit 9815d97
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
3 changes: 1 addition & 2 deletions rayon-core/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,7 @@ impl Registry {

/// Waits for the worker threads to stop. This is used for testing
/// -- so we can check that termination actually works.
#[cfg(test)]
pub fn wait_until_stopped(&self) {
pub(crate) fn wait_until_stopped(&self) {
for info in &self.thread_infos {
info.stopped.wait();
}
Expand Down
34 changes: 34 additions & 0 deletions rayon-core/src/thread_pool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,40 @@ impl ThreadPool {
&DEFAULT_THREAD_POOL
}

/// Creates a scoped thread pool
pub fn scoped_pool<F, R, H>(builder: ThreadPoolBuilder,
main_handler: H,
with_pool: F) -> Result<R, ThreadPoolBuildError>
where F: FnOnce(&ThreadPool) -> R,
H: Fn(&mut FnMut()) + Send + Sync
{
struct Handler(*const ());
unsafe impl Send for Handler {}
unsafe impl Sync for Handler {}

let handler = Handler(&main_handler as *const _ as *const ());

let builder = builder.main_handler(move |_, worker| {
let handler = unsafe { &*(handler.0 as *const H) };
handler(worker);
});

let pool = builder.build()?;

struct JoinRegistry(Arc<Registry>);

impl Drop for JoinRegistry {
fn drop(&mut self) {
self.0.terminate();
self.0.wait_until_stopped();
}
}

let _join_registry = JoinRegistry(pool.registry.clone());

Ok(with_pool(&pool))
}

/// Executes `op` within the threadpool. Any attempts to use
/// `join`, `scope`, or parallel iterators will then operate
/// within that threadpool.
Expand Down

0 comments on commit 9815d97

Please sign in to comment.