1 // Rust-101, Part 15: Mutex, Interior Mutability (cont.), RwLock, Sync
2 // ===================================================================
4 use std::sync::{Arc, Mutex};
7 //@ We already saw that we can use `Arc` to share memory between threads. However, `Arc` can only provide *read-only*
8 //@ access to memory: Since there is aliasing, Rust cannot, in general, permit mutation. To implement shared-memory
9 //@ concurrency, we need to have aliasing and permutation - following, of course, some strict rules to make sure
10 //@ there are no data races. In Rust, shared-memory concurrency is obtained through *interior mutability*,
11 //@ which we already discussed in a single-threaded context in part 12.
13 //@ The most basic type for interior mutability that supports concurrency is [`Mutex<T>`](http://doc.rust-lang.org/stable/std/sync/struct.Mutex.html).
14 //@ This type implements *critical sections* (or *locks*), but in a data-driven way: One has to specify
15 //@ the type of the data that's protected by the mutex, and Rust ensures that the data is *only* accessed
16 //@ through the mutex. In other words, "lock data, not code" is actually enforced by the type system, which
17 //@ becomes possible because of the discipline of ownership and borrowing.
19 //@ As an example, let us write a concurrent counter. As usual in Rust, we first have to think about our data layout:
20 //@ That will be `Mutex<usize>`. Of course, we want multiple threads to have access to this `Mutex`, so we wrap it in an `Arc`.
22 //@ Rather than giving every field a name, a struct can also be defined by just giving a sequence of types (similar
23 //@ to how a variant of an `enum` is defined). This is called a *tuple struct*. It is often used when constructing
24 //@ a *newtype*, as we do here: `ConcurrentCounter` is essentially just a new name for `Arc<Mutex<usize>>`. However,
25 //@ is is a locally declared types, so we can give it an inherent implementation and implement traits for it. Since the
26 //@ field is private, nobody outside this module can even know the type we are wrapping.
28 // The derived `Clone` implementation will clone the `Arc`, so all clones will actually talk about the same counter.
30 struct ConcurrentCounter(Arc<Mutex<usize>>);
32 impl ConcurrentCounter {
33 // The constructor just wraps the constructors of `Arc` and `Mutex`.
34 pub fn new(val: usize) -> Self {
35 ConcurrentCounter(Arc::new(Mutex::new(val))) /*@*/
38 // The core operation is, of course, `increment`.
39 pub fn increment(&self, by: usize) {
40 // `lock` on a mutex returns a guard, very much like `RefCell`. The guard gives access to the data contained in the mutex.
41 //@ (We will discuss the `unwrap` soon.) `.0` is how we access the first component of a tuple or a struct.
42 let mut counter = self.0.lock().unwrap();
43 //@ The guard is a smart pointer to the content.
44 *counter = *counter + by;
45 //@ At the end of the function, `counter` is dropped and the mutex is available again.
46 //@ This can only happen when full ownership of the guard is given up. In particular, it is impossible for us
47 //@ to borrow some of its content, release the lock of the mutex, and subsequently access the protected data without holding
48 //@ the lock. Enforcing the locking discipline is expressible in the Rust type system, so we don't have to worry
49 //@ about data races *even though* we are mutating shared memory!
51 //@ One of the subtle aspects of locking is *poisoning*. If a thread panics while it holds a lock, it could leave the
52 //@ data-structure in a bad state. The lock is hence considered *poisoned*. Future attempts to `lock` it will fail.
53 //@ Above, we simply assert via `unwrap` that this will never happen. Alternatively, we could have a look at the poisoned
54 //@ state and attempt to recover from it.
57 // The function `get` returns the current value of the counter.
58 pub fn get(&self) -> usize {
59 let counter = self.0.lock().unwrap(); /*@*/
64 // Now our counter is ready for action.
66 let counter = ConcurrentCounter::new(0);
68 // We clone the counter for the first thread, which increments it by 2 every 15ms.
69 let counter1 = counter.clone();
70 let handle1 = thread::spawn(move || {
73 counter1.increment(2);
77 // The second thread increments the counter by 3 every 20ms.
78 let counter2 = counter.clone();
79 let handle2 = thread::spawn(move || {
82 counter2.increment(3);
86 // Now we watch the threads working on the counter.
89 println!("Current value: {}", counter.get());
92 // Finally, we wait for all the threads to finish to be sure we can catch the counter's final value.
93 handle1.join().unwrap();
94 handle2.join().unwrap();
95 println!("Final value: {}", counter.get());
98 // **Exercise 15.1**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by
99 // `by` *only if* the current value is `test`.
101 // **Exercise 15.2**: Rather than panicking in case the lock is poisoned, we can use `into_innter` on the error to recover
102 // the data inside the lock. Change the code above to do that. Try using `unwrap_or_else` for this job.
105 //@ Besides `Mutex`, there's also [`RwLock`](http://doc.rust-lang.org/stable/std/sync/struct.RwLock.html), which
106 //@ provides two ways of locking: One that grants only read-only access, to any number of concurrent readers, and another one
107 //@ for exclusive write access. Notice that this is the same pattern we already saw with shared vs. mutable borrows. Hence
108 //@ another way of explaining `RwLock` is to say that it is like `RefCell`, but works even for concurrent access. Rather than
109 //@ panicking when the data is already borrowed, `RwLock` will of course block the current thread until the lock is available.
110 //@ In this view, `Mutex` is a stripped-down version of `RwLock` that does not distinguish readers and writers.
112 // **Exercise 15.3**: Change the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time.
115 //@ Clearly, if we had used `RefCell` rather than `Mutex`, the code above could not work: `RefCell` is not prepared for
116 //@ multiple threads trying to access the data at the same time. How does Rust make sure that we don't accidentally use
117 //@ `RefCell` across multiple threads?
119 //@ In part 13, we talked about types that are marked `Send` and thus can be moved to another thread. However, we did *not*
120 //@ talk about the question whether a borrow is `Send`. For `&mut T`, the answer is: It is `Send` whenever `T` is send.
121 //@ `&mut` allows moving values back and forth, it is even possible to [`swap`](http://doc.rust-lang.org/beta/std/mem/fn.swap.html)
122 //@ the contents of two mutably borrowed values. So in terms of concurrency, sending a mutable borrow is very much like
123 //@ sending full ownership, in the sense that it can be used to move the object to another thread.
125 //@ But what about `&T`, a shared borrow? Without interior mutability, it would always be all-right to send such values.
126 //@ After all, no mutation can be performed, so there can be as many threads accessing the data as we like. In the
127 //@ presence of interior mutability though, the story gets more complicated. Rust introduces another marker trait for
128 //@ this purpose: `Sync`. A type `T` is `Sync` if and only if `&T` is `Send`. Just like `Send`, `Sync` has a default implementation
129 //@ and is thus automatically implemented for a data-structure *if* all its members implement it.
131 //@ Since `Arc` provides multiple threads with a shared borrow of its content, `Arc<T>` is only `Send` if `T` is `Sync`.
132 //@ So if we had used `RefCell` above, which is *not* `Sync`, Rust would have caught that mistake. Notice however that
133 //@ `RefCell` *is* `Send`: If ownership of the entire cell is moved to another thread, it is still not possible for several
134 //@ threads to try to access the data at the same time.
136 //@ Almost all the types we saw so far are `Sync`, with the exception of `Rc`. Remember that a shared borrow is good enough
137 //@ for cloning, and we don't want other threads to clone our local `Rc`, so it must not be `Sync`. The rule of `Mutex`
138 //@ is to enforce synchronization, so it should not be entirely surprising that `Mutex<T>` is `Send` *and* `Sync` provided that
141 //@ You may be curious whether there is a type that's `Sync`, but not `Send`. There are indeed rather esoteric examples
142 //@ of such types, but that's not a topic I want to go into. In case you are curious, there's a
143 //@ [Rust RFC](https://github.com/rust-lang/rfcs/blob/master/text/0458-send-improvements.md), which contains a type `RcMut` that would be `Sync` and not `Send`.
144 //@ You may also be interested in [this blog post](https://huonw.github.io/blog/2015/02/some-notes-on-send-and-sync/) on the topic.
146 //@ [index](main.html) | [previous](part14.html) | [next](main.html)