Browse Source

Locking workers

master
Noelle 4 years ago
parent
commit
12f8e8dca6
1 changed files with 25 additions and 6 deletions
  1. 25
    6
      src/lib.rs

+ 25
- 6
src/lib.rs View File

@@ -1,28 +1,39 @@
use std::thread;
use std::sync::{mpsc, Mutex, Arc};

pub struct ThreadPool{
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}

type Job = Box<dyn FnOnce() + Send + 'static>;

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));
workers.push(Worker::new(id, Arc::clone(&receiver)));
}

ThreadPool {
workers
workers,
sender,
}

}

pub fn execute<F>(&self, f: F)
where F: FnOnce() + Send + 'static {

where F: FnOnce() + Send + 'static
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}

// pub fn spawn<F, T>(f: F) -> JoinHandle<T>
@@ -41,8 +52,16 @@ struct Worker {
}

impl Worker {
fn new(id: usize) -> Worker {
let thread = thread::spawn(|| {});
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || {
loop {
let job = receiver.lock().unwrap().recv().unwrap();

println!("Worker {} got a job, executing.", id);

job();
}
});

Worker {
id,

Loading…
Cancel
Save