WIP workers
This commit is contained in:
parent
a90cd5cc6b
commit
912624a132
|
@ -1,3 +1,6 @@
|
|||
extern crate httpserve;
|
||||
use httpserve::ThreadPool;
|
||||
|
||||
use std::io::prelude::*;
|
||||
use std::fs;
|
||||
use std::net::TcpStream;
|
||||
|
@ -10,13 +13,13 @@ fn main() {
|
|||
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
|
||||
let counter = Arc::new(Mutex::new(0usize));
|
||||
|
||||
//let pool = ThreadPool::new(100);
|
||||
let tasks = ThreadPool::new(100);
|
||||
|
||||
for stream in listener.incoming() {
|
||||
let stream = stream.unwrap();
|
||||
let counter = Arc::clone(&counter);
|
||||
|
||||
thread::spawn(move || {
|
||||
tasks.queue(move || {
|
||||
{
|
||||
// in a subscope to release borrow automatically
|
||||
let mut count = counter.lock().unwrap();
|
|
@ -0,0 +1,69 @@
|
|||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
|
||||
trait FnBox {
|
||||
fn call_box(self: Box<Self>);
|
||||
}
|
||||
|
||||
impl<F: FnOnce()> FnBox for F {
|
||||
fn call_box(self: Box<F>) {
|
||||
(*self)();
|
||||
}
|
||||
}
|
||||
|
||||
type Job = Box<dyn FnOnce() + Send + 'static>;
|
||||
|
||||
struct Worker {
|
||||
id: usize,
|
||||
thread: thread::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
|
||||
Worker {
|
||||
id,
|
||||
thread: thread::spawn(move || {
|
||||
loop {
|
||||
let job = receiver.lock().expect("unrecoverable poisened panicked thread state").recv().unwrap();
|
||||
|
||||
println!("such busy, so worker #{}!", id);
|
||||
|
||||
job.call_box();
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ThreadPool {
|
||||
workers: Vec<Worker>,
|
||||
sender: mpsc::Sender<Job>,
|
||||
}
|
||||
|
||||
impl ThreadPool {
|
||||
pub fn new(size: usize) -> ThreadPool {
|
||||
assert!(size > 0);
|
||||
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let receiver = Arc::new(Mutex::new(receiver));
|
||||
|
||||
let mut workers = Vec::with_capacity(size);
|
||||
|
||||
for id in 0..size {
|
||||
workers.push(Worker::new(id, Arc::clone(&receiver)))
|
||||
}
|
||||
|
||||
//ThreadPool.max = size;
|
||||
ThreadPool {
|
||||
workers,
|
||||
sender,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run<F: FnOnce() + Send + 'static>(&self, task: F)
|
||||
{
|
||||
let task = Box::new(task);
|
||||
self.sender.send(task).unwrap();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue