[][src]Struct threadpool::ThreadPool

pub struct ThreadPool { /* fields omitted */ }

Abstraction of a thread pool for basic parallelism.

Methods

impl ThreadPool[src]

pub fn new(num_threads: usize) -> ThreadPool[src]

Creates a new thread pool capable of executing num_threads number of jobs concurrently.

Panics

This function will panic if num_threads is 0.

Examples

Create a new thread pool capable of executing four jobs concurrently:

use threadpool::ThreadPool;

let pool = ThreadPool::new(4);

pub fn with_name(name: String, num_threads: usize) -> ThreadPool[src]

Creates a new thread pool capable of executing num_threads number of jobs concurrently. Each thread will have the name name.

Panics

This function will panic if num_threads is 0.

Examples

use std::thread;
use threadpool::ThreadPool;

let pool = ThreadPool::with_name("worker".into(), 2);
for _ in 0..2 {
    pool.execute(|| {
        assert_eq!(
            thread::current().name(),
            Some("worker")
        );
    });
}
pool.join();

pub fn new_with_name(name: String, num_threads: usize) -> ThreadPool[src]

Deprecated since 1.4.0:

use ThreadPool::with_name

Deprecated: Use ThreadPool::with_name

pub fn execute<F>(&self, job: F) where
    F: FnOnce() + Send + 'static, 
[src]

Executes the function job on a thread in the pool.

Examples

Execute four jobs on a thread pool that can run two jobs concurrently:

use threadpool::ThreadPool;

let pool = ThreadPool::new(2);
pool.execute(|| println!("hello"));
pool.execute(|| println!("world"));
pool.execute(|| println!("foo"));
pool.execute(|| println!("bar"));
pool.join();

pub fn queued_count(&self) -> usize[src]

Returns the number of jobs waiting to executed in the pool.

Examples

use threadpool::ThreadPool;
use std::time::Duration;
use std::thread::sleep;

let pool = ThreadPool::new(2);
for _ in 0..10 {
    pool.execute(|| {
        sleep(Duration::from_secs(100));
    });
}

sleep(Duration::from_secs(1)); // wait for threads to start
assert_eq!(8, pool.queued_count());

pub fn active_count(&self) -> usize[src]

Returns the number of currently active threads.

Examples

use threadpool::ThreadPool;
use std::time::Duration;
use std::thread::sleep;

let pool = ThreadPool::new(4);
for _ in 0..10 {
    pool.execute(move || {
        sleep(Duration::from_secs(100));
    });
}

sleep(Duration::from_secs(1)); // wait for threads to start
assert_eq!(4, pool.active_count());

pub fn max_count(&self) -> usize[src]

Returns the maximum number of threads the pool will execute concurrently.

Examples

use threadpool::ThreadPool;

let mut pool = ThreadPool::new(4);
assert_eq!(4, pool.max_count());

pool.set_num_threads(8);
assert_eq!(8, pool.max_count());

pub fn panic_count(&self) -> usize[src]

Returns the number of panicked threads over the lifetime of the pool.

Examples

use threadpool::ThreadPool;

let pool = ThreadPool::new(4);
for n in 0..10 {
    pool.execute(move || {
        // simulate a panic
        if n % 2 == 0 {
            panic!()
        }
    });
}
pool.join();

assert_eq!(5, pool.panic_count());

pub fn set_threads(&mut self, num_threads: usize)[src]

Deprecated since 1.3.0:

use ThreadPool::set_num_threads

pub fn set_num_threads(&mut self, num_threads: usize)[src]

Sets the number of worker-threads to use as num_threads. Can be used to change the threadpool size during runtime. Will not abort already running or waiting threads.

Panics

This function will panic if num_threads is 0.

Examples

use threadpool::ThreadPool;
use std::time::Duration;
use std::thread::sleep;

let mut pool = ThreadPool::new(4);
for _ in 0..10 {
    pool.execute(move || {
        sleep(Duration::from_secs(100));
    });
}

sleep(Duration::from_secs(1)); // wait for threads to start
assert_eq!(4, pool.active_count());
assert_eq!(6, pool.queued_count());

// Increase thread capacity of the pool
pool.set_num_threads(8);

sleep(Duration::from_secs(1)); // wait for new threads to start
assert_eq!(8, pool.active_count());
assert_eq!(2, pool.queued_count());

// Decrease thread capacity of the pool
// No active threads are killed
pool.set_num_threads(4);

assert_eq!(8, pool.active_count());
assert_eq!(2, pool.queued_count());

pub fn join(&self)[src]

Block the current thread until all jobs in the pool have been executed.

Calling join on an empty pool will cause an immediate return. join may be called from multiple threads concurrently. A join is an atomic point in time. All threads joining before the join event will exit together even if the pool is processing new jobs by the time they get scheduled.

Calling join from a thread within the pool will cause a deadlock. This behavior is considered safe.

Examples

use threadpool::ThreadPool;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

let pool = ThreadPool::new(8);
let test_count = Arc::new(AtomicUsize::new(0));

for _ in 0..42 {
    let test_count = test_count.clone();
    pool.execute(move || {
        test_count.fetch_add(1, Ordering::Relaxed);
    });
}

pool.join();
assert_eq!(42, test_count.load(Ordering::Relaxed));

Trait Implementations

impl Clone for ThreadPool[src]

fn clone(&self) -> ThreadPool[src]

Cloning a pool will create a new handle to the pool. The behavior is similar to Arc.

We could for example submit jobs from multiple threads concurrently.

use threadpool::ThreadPool;
use std::thread;
use std::sync::mpsc::channel;

let pool = ThreadPool::with_name("clone example".into(), 2);

let results = (0..2)
    .map(|i| {
        let pool = pool.clone();
        thread::spawn(move || {
            let (tx, rx) = channel();
            for i in 1..12 {
                let tx = tx.clone();
                pool.execute(move || {
                    tx.send(i).expect("channel will be waiting");
                });
            }
            drop(tx);
            if i == 0 {
                rx.iter().fold(0, |accumulator, element| accumulator + element)
            } else {
                rx.iter().fold(1, |accumulator, element| accumulator * element)
            }
        })
    })
    .map(|join_handle| join_handle.join().expect("collect results from threads"))
    .collect::<Vec<usize>>();

assert_eq!(vec![66, 39916800], results);

impl Debug for ThreadPool[src]

impl Default for ThreadPool[src]

Create a thread pool with one thread per CPU. On machines with hyperthreading, this will create one thread per hyperthread.

impl Eq for ThreadPool[src]

impl PartialEq<ThreadPool> for ThreadPool[src]

fn eq(&self, other: &ThreadPool) -> bool[src]

Check if you are working with the same pool

use threadpool::ThreadPool;

let a = ThreadPool::new(2);
let b = ThreadPool::new(2);

assert_eq!(a, a);
assert_eq!(b, b);

assert!(a != b);
assert!(b != a);

Auto Trait Implementations

impl !RefUnwindSafe for ThreadPool

impl Send for ThreadPool

impl !Sync for ThreadPool

impl Unpin for ThreadPool

impl !UnwindSafe for ThreadPool

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.