#thread-manager

blackhole

…to throw your threads into

20 releases (breaking)

0.18.0 Dec 12, 2020
0.17.1 Aug 15, 2019
0.16.0 Jul 7, 2019
0.14.0 Mar 28, 2019

#136 in Concurrency

Download history 6/week @ 2021-06-27 9/week @ 2021-07-04 7/week @ 2021-07-11 83/week @ 2021-07-18 28/week @ 2021-07-25 46/week @ 2021-08-01 6/week @ 2021-08-08 24/week @ 2021-08-15 12/week @ 2021-08-22 1/week @ 2021-08-29 3/week @ 2021-09-05 3/week @ 2021-09-12 3/week @ 2021-09-19 20/week @ 2021-09-26 23/week @ 2021-10-03 3/week @ 2021-10-10

109 downloads per month
Used in 3 crates

Custom license

22KB
310 lines

Black Hole




lib.rs:

Black Hole

...to throw your threads into.

Project

Features

Simple thread manager.

Design

It uses a channel and one job manager thread:

  • When you throw a new job, it checks for active job count.

    • If that count is smaller than limit, it spawns a new runner thread to run that job.

    • If that count is equal to limit:

      • If job queue is smaller than limit, it pushes the job into the queue.
      • Otherwise the job is discarded. An error message is printed to stderr. And the job is returned to you for recovery.
  • When the runner thread finishes the first job, it contacts job manager to ask for new jobs to run. If there are no new jobs, it finishes itself and notifies job manager about that.

  • When job manager receives job-finished-message, it checks job queue to spawn new runner threads, if necessary.

Examples

use blackhole::{ActiveLimit, BlackHole, Job};

/// # This job takes a `usize`, if it's odd, sends it to Printer
struct Handler {
    data: usize,
}

impl Job for Handler {

    fn run(&mut self) -> Option<Box<dyn Job>> {
        match self.data % 2 {
            0 => None,
            _ => Some(Box::new(Printer { data: self.data })),
        }
    }

}

/// # This job prints data and does nothing else
struct Printer {
    data: usize,
}

impl Job for Printer {

    fn run(&mut self) -> Option<Box<dyn Job>> {
        println!("{}", self.data);
        None
    }

}

let active_limit: ActiveLimit = 4;
let queue_limit: usize = 10;
let black_hole = BlackHole::make(active_limit, queue_limit).unwrap();
for i in 0 .. queue_limit * 2 {
    match black_hole.throw(Handler { data: i }) {
        Ok(None) => println!("Job is accepted"),
        // If job is discarded, it will be sent back here.
        Ok(Some(job)) => {
            eprintln!("Job is discarded! We'll run it ourselves!");
            blackhole::run_to_end(job);
        },
        Err(err) => {
            eprintln!("BlackHole... exploded: {}", err);
            break;
        },
    };
}
black_hole.escape_on_idle().unwrap();

No runtime deps