Hey, after watching episode 9 I wanted to play around with another way of doing this: Instead of using a Mutex, we can also create a new hash map each time and combine them later on in a reduce. And Rayon has a pretty nice way of doing that.
I have not done any benchmarks whatsoever. See commit messages for more details.
This is very unhelpful: error[E0387]: cannot borrow data mutably in a captured outer variable in an `Fn` closure --> src/main.rs:30:57 | 30 | .for_each(|filename| tally_words(filename, &mut words).unwrap()); | ^^^^^ | help: consider changing this closure to take self by mutable reference --> src/main.rs:30:19 | 30 | .for_each(|filename| tally_words(filename, &mut words).unwrap()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This creates a new HashMap in each `tally_words` call. We can thus omit using a Mutex. Instead of doing `for_each` with side effects, we use `reduce` (Rayon's parallel version of it) to build the final map of words. The reason I used the im crate is because it has a very nice `union_with` method on its HashMap; you can also replace `im::HashMap` with `im::OrdMap` if you want to get sorted output directly. I have no idea if this is faster, but it does show a different way of using concurrency.