Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,26 @@ mod tests {
let results = Vec::<TestTask>::new().par_run().unwrap();
assert!(results.is_empty());
}

#[test]
fn test_builder() {
let task = TestTask(10);
let builder = std::thread::Builder::new().name("custom_thread".to_string());
let handle = task.start_with_builder(builder);
assert_eq!(handle.join().unwrap(), 20);

struct BuilderTask;

impl Runnable for BuilderTask {
type Output = String;

fn run(self) -> Self::Output {
std::thread::current().name().unwrap().to_string()
}
}

let builder = std::thread::Builder::new().name("custom_thread".to_string());
let handle = BuilderTask.start_with_builder(builder);
assert_eq!(handle.join().unwrap(), "custom_thread".to_string());
}
}
14 changes: 13 additions & 1 deletion src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,24 @@ pub trait Thread: Runnable {
/// assert_eq!(handle.join().unwrap(), 12);
/// ```
fn start(self) -> std::thread::JoinHandle<Self::Output>;

/// Spawns a new thread using a custom [`std::thread::Builder`] to execute the `run` method.
fn start_with_builder(
self,
builder: std::thread::Builder,
) -> std::thread::JoinHandle<Self::Output>;
}

impl<T: Runnable> Thread for T {
fn start(self) -> std::thread::JoinHandle<Self::Output> {
std::thread::spawn(move || self.run())
}
fn start_with_builder(
self,
builder: std::thread::Builder,
) -> std::thread::JoinHandle<Self::Output> {
builder.spawn(move || self.run()).unwrap()
}
}

/// An extension trait that provides a method to run multiple [`Runnable`]'s in parallel.
Expand Down Expand Up @@ -127,7 +139,7 @@ impl<T: Runnable> ParallelRun for Vec<T> {
if threads == 0 {
return Ok(Vec::new());
}

let chunk_size = self.len().div_ceil(threads);

let mut iter = self.into_iter();
Expand Down