book icon indicating copy to clipboard operation
book copied to clipboard

Listing 20-15 Commentary improvement

Open Yung-Beef opened this issue 1 year ago • 0 comments
trafficstars

URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch20-02-multithreaded.html

Description of the problem: It's not clear why you can't use

impl Worker {
    fn new(id: usize) -> Worker {
        Worker {
            id, 
            thread: thread::spawn(|| {}) },
    }
}

I wrote it out like that, thinking I'd found a more concise way to do it and feeling cool, and it wasn't a problem until I got down to 20-18 (where you've added receiver to the closure and put receiver inside an Arc and Mutex) where I couldn't get it to work until I rewrote this method as how the book writes it.

image

image

Suggested fix: Explain below listing 20-15 why the thread needs to be spawned outside of the created and returned Worker struct.

Yung-Beef avatar Aug 15 '24 13:08 Yung-Beef