Joemoor94
Joemoor94

Reputation: 173

Why is receiver declared with Receiver<Job>?

Here is the full code from the last chapter in the Rust book, under multi-threading a web-server.

use std::thread;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::mpsc;

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

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

impl ThreadPool {
    /// Create a new ThreadPool.
    ///
    /// The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    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 { workers, sender }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        self.sender.send(job).unwrap();
    }
}

struct Worker {
    id: usize,
    thread: thread::JoinHandle<()>,
}

impl Worker {
    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, thread }
    }
}

I was wondering why the new() function when implementing Worker receives an Arc<Mutex<mpsc::Receiver<Job>>> type.

I would assume it would just be Arc<Mutex<mpsc::Receiver>>. Same with sender in ThreadPool. How does mpsc::channel() know to return those types in the ThreadPool implementation?

Upvotes: 2

Views: 143

Answers (1)

vallentin
vallentin

Reputation: 26167

Up front T in Sender<T> (and Receiver<T>) is unknown. However, when you attempt to create a ThreadPool with sender, then the compiler can infer that T must be Job. Because ThreadPool's sender field is a Sender<Job>.

Given that the mpsc::channel() returns a Sender<T> and Receiver<T> with the same T, then if Sender<T> is Sender<Job>, then Receiver<T> must also be Receiver<Job>.

This becomes apparent when you take a look at the function signature of mpsc::channel():

pub fn channel<T>() -> (Sender<T>, Receiver<T>)

Upvotes: 4

Related Questions