Page
Another strange question is: we use _left and _right to name it. What is the underscore? We do not plan to use these two variables when locking. We just want to get it. Therefore, Rust warns us not to use these values. By using underscores, We tell rust that's what we want, and it doesn't throw a warning.
How do I release the lock? _left and _right leave their scopes and are freed automatically. Let table = arc::new (Table {forks:vec![
Mutex::new (()),
Mutex::new (()),
Mutex::new (()),
Mutex::new (()),
Mutex::new (()),
]});
Next, in the main function, we used a new table and then wrapped it with arc<t>. " Arc "means" atomic reference count (atomic reference count) ", we need to share the table across multiple threads. When we share, it increases the chance of reference counting, and then when the thread ends, the reference count is reduced.
Let philosophers = vec! [
Philosopher::new ("Baruch Spinoza", 0, 1),
Philosopher::new ("Gilles Deleuze",
Philosopher::new ("Karl Marx", 2, 3),
Philosopher::new ("Friedrich Nietzsche", 3,4),
Philosopher::new ("Michel Foucault", 0,4),
];
We need to pass in the left and right arguments in the philosophers constructor. But there is one detail and it is important. If you look at the form of a constructor, you will find that it is symmetrical until the end. Michel Foucault (originally written as Monsieur Foucault) should have used 4,0 such an entry, but the use of 0,4 such a parameter. This is to prevent the deadlock from occurring. In fact, one of the philosophers is left-handed! This is a way to solve the philosopher's problem, and it seems to me to be the simplest.
Let handles:vec<_> = Philosophers.into_iter (). Map (|p| {
Let table = Table.clone ();
Thread::spawn (Move | | {
P.eat (&table);
})
}). Collect ();
Finally, in the loop of map ()/collect (), we call the Table.clone () method. The Clone () method acting on the Arc<t> object increases its reference count, It then reduces the reference count when it leaves its scope. You will find that we have introduced a new binding table that will allude to the original table. This technique is often used so that you don't have to use two different variable names.
Page 55
Here, our program can work properly! Only two philosophers at a time can dine, so you'll get the following output:
Congratulations! You have completed a classic concurrency problem using the rust language.
Rust Chinese Translation 9