>;
fn main() -> Result<()> {
// Come up with some work that needs to be performed. Let's pretend to
// perform work on each file in the current directory.
let mut files = Vec::new();
for entry in fs::read_dir(".")? {
files.push(entry?.path());
}
files.sort();
// Build a thread pool with one thread per cpu.
let cpus = num_cpus::get();
let pool = ThreadPoolBuilder::new().num_threads(cpus).build()?;
// Spin up the right number of worker threads. They will write to stderr.
let oqueue = Sequencer::stderr();
pool.scope(|scope| {
for _ in 0..cpus {
scope.spawn(|_| worker(&oqueue, &files));
}
});
Ok(())
}
fn worker(oqueue: &Sequencer, inputs: &[PathBuf]) {
// Perform tasks indicated by the sequencer.
loop {
let task = oqueue.begin();
match inputs.get(task.index) {
Some(path) => work(task, path),
None => return,
}
}
}
fn work(task: Task, path: &Path) {
// Produce output by writing to the task.
write!(task, "evaluating ");
task.bold();
writeln!(task, "{}", path.display());
// Do some expensive work...
let string = path.to_string_lossy();
thread::sleep(Duration::from_millis(150 * string.len() as u64));
// ... which may fail or succeed.
if string.contains('c') {
task.bold_color(Red);
write!(task, " ERROR");
task.reset_color();
writeln!(task, ": path contains the letter 'c'");
}
}
```
The output of this program is guaranteed to display tasks in the intended
sorted order and non-interleaved. Tasks will make progress in parallel
without needing to wait to perform output. All output will appear the
earliest possible including one task in real time at all times.
evaluating ./.git
evaluating ./.gitignore
evaluating ./Cargo.lock
ERROR: path contains the letter 'c'
evaluating ./Cargo.toml
evaluating ./LICENSE-APACHE
evaluating ./LICENSE-MIT
evaluating ./README.md
evaluating ./examples
evaluating ./src
ERROR: path contains the letter 'c'
evaluating ./target
## Further reading
- The [`oqueue::Sequencer`][Sequencer] documentation covers some different
techniques for distributing work items across tasks.
- The [`oqueue::Task`][Task] documentation shows the APIs for setting
output color and writing output to a task.
[Sequencer]: https://docs.rs/oqueue/0.1/oqueue/struct.Sequencer.html
[Task]: https://docs.rs/oqueue/0.1/oqueue/struct.Task.html
#### License
Licensed under either of Apache License, Version
2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.