google / comprehensive-rust

This is the Rust course used by the Android team at Google. It provides you the material to quickly teach Rust.
https://google.github.io/comprehensive-rust/
Apache License 2.0
26.74k stars 1.58k forks source link

Make `Fork` useful in Dinning Philosopher exercises #2126

Open mgeisler opened 1 month ago

mgeisler commented 1 month ago

Currently, we define the Fork type like this:

struct Fork;

Because there is nothing to do with a Fork, people get compiler warnings when locking a Mutex<Fork>...

We should fix this: an idea would be to let the fork remember the number of times it has been used:

struct Fork {
    usages: usize,
}

Another idea would be to remember the usage count per philosopher:

struct Fork {
    usages: HashMap<String, usize>,
}

That would give people something to do with the forks, thus solving the problem of the unused variables.

It would also allow people to inspect the forks afterwards to determine if their implementation is fair. For that to make sense, we would need to change the exercise to let each philosopher-thread run for a given amount of time, not a given number of iterations.

djmitche commented 1 month ago

This is a fairly common pattern - it represents locking critical sections (code) rather than data. It's more of a Java style of locking, but in some cases (such as this) it makes sense.

The exercise is sort of artificial, but in a real-life scenario where I wanted to use an empty struct, I would be a bit grumpy if compiler warnings forced me to put a dummy integer in there.

I ran the solution in the playground and I don't see any compiler warnings. What are people seeing?