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
impl ThreadPool
Sourcepub fn new(worker: usize) -> Result<ThreadPool, FailedToSpawnThread>
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
Sourcepub fn execute<F>(&self, job: F) -> Result<(), FailedToSendJob>
pub fn execute<F>(&self, job: F) -> Result<(), FailedToSendJob>
Trait Implementations§
Source§impl Debug for ThreadPool
impl Debug for ThreadPool
Source§impl Drop for ThreadPool
impl Drop for ThreadPool
Source§fn drop(&mut self)
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§
impl Freeze for ThreadPool
impl !RefUnwindSafe for ThreadPool
impl Send for ThreadPool
impl Sync for ThreadPool
impl Unpin for ThreadPool
impl !UnwindSafe for ThreadPool
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more