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