Skip to content

Commit

Permalink
Add ThreadPoolBuilder::build_scoped()
Browse files Browse the repository at this point in the history
  • Loading branch information
cuviper committed Feb 19, 2019
1 parent d19d6fe commit 7912c0c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
26 changes: 26 additions & 0 deletions rayon-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,32 @@ impl ThreadPoolBuilder {
thread_pool::build(self)
}

/// Create a scoped `ThreadPool` initialized using this configuration.
///
/// The threads in this pool will start by calling `wrapper`, which should
/// do initialization and continue by calling `ThreadBuilder::run()`.
pub fn build_scoped<W, F, R>(self, wrapper: W, with_pool: F) -> Result<R, ThreadPoolBuildError>
where
W: Fn(ThreadBuilder) + Sync, // expected to call `run()`
F: FnOnce(&ThreadPool) -> R,
{
crossbeam::scope(|scope| {
let wrapper = &wrapper;
let pool = self.spawn(|thread| {
let mut builder = scope.builder();
if let Some(name) = thread.name() {
builder = builder.name(name.to_string());
}
if let Some(size) = thread.stack_size() {
builder = builder.stack_size(size);
}
builder.spawn(move || wrapper(thread))?;
Ok(())
})?;
Ok(with_pool(&pool))
})
}

/// Create a new `ThreadPool` initialized using this configuration and a
/// custom function for spawning threads.
///
Expand Down
37 changes: 35 additions & 2 deletions rayon-core/tests/scoped_threadpool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ struct Local(i32);
scoped_thread_local!(static LOCAL: Local);

#[test]
fn scoped_tls_missing() {
fn missing_scoped_tls() {
LOCAL.set(&Local(42), || {
let pool = ThreadPoolBuilder::new()
.build()
Expand All @@ -26,7 +26,7 @@ fn scoped_tls_missing() {
}

#[test]
fn scoped_tls_threadpool() {
fn spawn_scoped_tls_threadpool() {
LOCAL.set(&Local(42), || {
LOCAL.with(|x| {
crossbeam::scope(|scope| {
Expand Down Expand Up @@ -64,3 +64,36 @@ fn scoped_tls_threadpool() {
});
});
}

#[test]
fn build_scoped_tls_threadpool() {
LOCAL.set(&Local(42), || {
LOCAL.with(|x| {
ThreadPoolBuilder::new()
.build_scoped(
move |thread| LOCAL.set(x, || thread.run()),
|pool| {
// The pool matches our local value.
pool.install(|| {
assert!(LOCAL.is_set());
LOCAL.with(|y| {
assert_eq!(x, y);
});
});

// If we change our local value, the pool is not affected.
LOCAL.set(&Local(-1), || {
pool.install(|| {
assert!(LOCAL.is_set());
LOCAL.with(|y| {
assert_eq!(x, y);
});
});
});
},
)
.expect("thread pool created");
// Internally, `crossbeam::scope` will wait for the threads to exit before returning.
});
});
}

0 comments on commit 7912c0c

Please sign in to comment.