Struct ThreadPool

Source
pub struct ThreadPool { /* private fields */ }
Expand description

This is where the thread will be pooled

It depend on how you add this package on your project you can either using Rust standard library or you can use crossbeam-channel, the API is the same even on different feature flag.

§Examples

use std::{
    io::Write,
    net::{TcpListener, TcpStream},
    thread,
    time::Duration,
};

use unknownrori_simple_thread_pool::{error::FailedToSendJob, ThreadPool};

fn handle_connection(mut stream: TcpStream) {
    thread::sleep(Duration::from_secs(2));

    let response = "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nHi!";

    stream.write_all(response.as_bytes()).unwrap();

    thread::sleep(Duration::from_secs(2));
}

fn main() -> Result<(), FailedToSendJob> {
    let pool = ThreadPool::new(2).unwrap();

    let socket = TcpListener::bind("127.0.0.1:8000").unwrap();
    println!("server started at http://127.0.0.1:8000");

    for stream in socket.incoming() {
        println!("Got stream!");
        match stream {
            Ok(stream) => pool.execute(|| handle_connection(stream))?,
            Err(_) => eprintln!("Something is wrong!"),
        }
    }

    Ok(())
}

Implementations§

Source§

impl ThreadPool

Source

pub fn new(worker: usize) -> Result<ThreadPool, FailedToSpawnThread>

Creates a new ThreadPool, with passed worker args for how many worker thread to be created

§Examples
use std::{thread, time::Duration};

use unknownrori_simple_thread_pool::{
    crossbeam_channel::unbounded,
    error::FailedToSendJob,
    ThreadPool,
};

fn main() -> Result<(), FailedToSendJob> {
    let pool = ThreadPool::new(2).unwrap();
    let (send, recv) = unbounded();

    pool.execute(move || {
        send.send(40).unwrap();
    })?;

    assert_eq!(recv.recv().unwrap(), 40);

    Ok(())
}
§Error

It will return an Err if cannot create thread worker

Source

pub fn execute<F>(&self, job: F) -> Result<(), FailedToSendJob>
where F: FnOnce() + Send + 'static,

Execute a job to worker thread, it’s require Closure with no param and no return

§Errors

This function will return an Err if the communication channel between worker thread and main thread is closed.

Trait Implementations§

Source§

impl Debug for ThreadPool

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for ThreadPool

Source§

fn drop(&mut self)

Make sure the ThreadPool do proper clean up with it’s thread workers

§Panic

May Panic if communcation between worker thread and main thread is closed or there are panic in worker thread.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.