1 // Rust-101, Part 15: Mutex, Interior Mutability (cont.), 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. If however,
9 //@ some care would be taken at run-time, then mutation would still be all right: We have to ensure that whenever
10 //@ someone changes the data, nobody else is looking at it. In other words, we need a *critical section* or (as it
11 //@ is called in Rust) a [`Mutex`](http://doc.rust-lang.org/stable/std/sync/struct.Mutex.html). Some other languages also call this a *lock*.
13 //@ As an example, let us write a concurrent counter. As usual in Rust, we first have to think about our data layout.
14 //@ In case of the mutex, this means we have to declare the type of the data that we want to be protected. In Rust,
15 //@ a `Mutex` protects data, not code - and it is impossible to access the data in any other way. This is generally considered
16 //@ good style, but other languages typically lack the ability to actually enforce this.
17 //@ Of course, we want multiple threads to have access to this `Mutex`, so we wrap it in an `Arc`.
19 //@ Rather than giving every field a name, a struct can also be defined by just giving a sequence of types (similar
20 //@ to how a variant of an `enum` is defined). This is called a *tuple struct*. It is often used when constructing
21 //@ a *newtype*, as we do here: `ConcurrentCounter` is essentially just a new name for `Arc<Mutex<usize>>`. However,
22 //@ is is a locally declared types, so we can give it an inherent implementation and implement traits for it. Since the
23 //@ field is private, nobody outside this module can even know the type we are wrapping.
25 // The derived `Clone` implementation will clone the `Arc`, so all clones will actually talk about the same counter.
27 struct ConcurrentCounter(Arc<Mutex<usize>>);
29 impl ConcurrentCounter {
30 // The constructor just wraps the constructors of `Arc` and `Mutex`.
31 pub fn new(val: usize) -> Self {
32 ConcurrentCounter(Arc::new(Mutex::new(val))) /*@*/
35 //@ The core operation is, of course, `increment`. The type may be surprising at first: A shared borrow?
36 //@ How can this be, since `increment` definitely modifies the counter? We already discussed above that `Mutex` is
37 //@ a way to get around this restriction in Rust. This phenomenon of data that can be mutated through a shared
38 //@ borrow is called *interior mutability*: We are changing the inner parts of the object, but seen from the outside,
39 //@ this does not count as "mutation". This stands in contrast to *exterior mutability*, which is the kind of
40 //@ mutability we saw so far, where one piece of data is replaced by something else of the same type. If you are familiar
41 //@ with languages like ML, you can compare this to how something of type `ref` permits mutation, even though it is
42 //@ itself a functional value (more precisely, a location) like all the others.
44 //@ Interior mutability breaks the rules of Rust that I outlined earlier: There is aliasing (a shared borrow) and mutation.
45 //@ The reason that this still works is careful programming of the primitives for interior mutability - in this case, that's
46 //@ `Mutex`. It has to ensure with dynamic checks, at run-time, that things don't fall apart. In particular, it has to ensure
47 //@ that the data covered by the mutex can only ever be accessed from inside a critical section. This is where Rust's type
48 //@ system comes into play: With its discipline of ownership and borrowing, it can enforce such rules. Let's see how this goes.
49 pub fn increment(&self, by: usize) {
50 // `lock` on a mutex returns a *guard*, giving access to the data contained in the mutex.
51 //@ (We will discuss the `unwrap` soon.) `.0` is how we access the first component of a tuple or a struct.
52 let mut counter = self.0.lock().unwrap();
53 //@ The guard is another example of a smart pointer, and it can be used as if it were a pointer to the data protected
55 *counter = *counter + by;
56 //@ At the end of the function, `counter` is dropped and the mutex is available again.
57 //@ This can only happen when full ownership of the guard is given up. In particular, it is impossible for us
58 //@ to borrow some of its content, release the lock of the mutex, and subsequently access the protected data without holding
59 //@ the lock. Enforcing the locking discipline is expressible in the Rust type system, so we don't have to worry
60 //@ about data races *even though* we are mutating shared memory!
62 //@ One of the subtle aspects of locking is *poisoning*. If a thread panics while it holds a lock, it could leave the
63 //@ data-structure in a bad state. The lock is hence considered *poisoned*. Future attempts to `lock` it will fail.
64 //@ Above, we simply assert via `unwrap` that this will never happen. Alternatively, we could have a look at the poisoned
65 //@ state and attempt to recover from it.
68 // The function `get` returns the current value of the counter.
69 pub fn get(&self) -> usize {
70 let counter = self.0.lock().unwrap(); /*@*/
75 // Now our counter is ready for action.
77 let counter = ConcurrentCounter::new(0);
79 // We clone the counter for the first thread, which increments it by 2 every 15ms.
80 let counter1 = counter.clone();
81 let handle1 = thread::spawn(move || {
84 counter1.increment(2);
88 // The second thread increments the counter by 3 every 20ms.
89 let counter2 = counter.clone();
90 let handle2 = thread::spawn(move || {
93 counter2.increment(3);
97 // Now we watch the threads working on the counter.
100 println!("Current value: {}", counter.get());
103 // Finally, we wait for all the threads to finish to be sure we can catch the counter's final value.
104 handle1.join().unwrap();
105 handle2.join().unwrap();
106 println!("Final value: {}", counter.get());
109 // **Exercise 14.1**: Besides `Mutex`, there's also [`RwLock`](http://doc.rust-lang.org/stable/std/sync/struct.RwLock.html), which
110 // provides two ways of locking: One that grants only read-only access, to any number of concurrent readers, and another one
111 // for exclusive write access. (Notice that this is the same pattern we already saw with shared vs. mutable borrows.) Change
112 // the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time.
114 // **Exercise 14.2**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by
115 // `by` *only if* the current value is `test`.
118 //@ In part 12, we talked about types that are marked `Send` and thus can be moved to another thread. However, we did *not*
119 //@ talk about the question whether a borrow is `Send`. For `&mut T`, the answer is: It is `Send` whenever `T` is send.
120 //@ `&mut` allows moving values back and forth, it is even possible to [`swap`](http://doc.rust-lang.org/beta/std/mem/fn.swap.html)
121 //@ the contents of two mutably borrowed values. So in terms of concurrency, sending a mutable borrow is very much like
122 //@ sending full ownership, in the sense that it can be used to move the object to another thread.
124 //@ But what about `&T`, a shared borrow? Without interior mutability, it would always be all-right to send such values.
125 //@ After all, no mutation can be performed, so there can be as many threads accessing the data as we like. In the
126 //@ presence of interior mutability though, the story gets more complicated. Rust introduces another marker trait for
127 //@ this purpose: `Sync`. A type `T` is `Sync` if `&T` is `Send`. Just like `Send`, `Sync` has a default implementation
128 //@ and is thus automatically implemented for a data-structure *if* all its members implement it.
130 //@ Almost all the types we saw so far are `Sync`, with the exception of `Rc`. Remember that a shared borrow is good enough
131 //@ for cloning, and we don't want other threads to clone our local `Rc`, so it must not be `Sync`. The rule of `Mutex`
132 //@ is to enforce synchronization, so it should not be entirely surprising that `Mutex<T>` is `Send` *and* `Sync` provided that
135 //@ In the next part, we will learn about a type called `RefCell` that is `Send`, but not `Sync`.
137 //@ You may be curious whether there is a type that's `Sync`, but not `Send`. There are indeed rather esoteric examples
138 //@ of such types, but that's not a topic I want to go into. In case you are curious, there's a
139 //@ [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`.
140 //@ 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.
142 // FIXME TODO some old outdated explanation FIXME TODO
144 //@ [`RefCell`](http://doc.rust-lang.org/beta/std/cell/struct.RefCell.html)
145 //@ [`is very much like `RwLock`, but it's not thread-safe: "Locking" is done without atomic operations.
146 //@ One can also see it as a dynamically checked version of Rust's usual borrowing rules. You have to explicitly say
147 //@ when you want to borrow the data in there shared, or mutably, and Rust will complain at run-time if you have
148 //@ a mutable borrow while any other borrow is active. You can then write programs that Rust may otherwise not
149 //@ accept. Sending a shared borrow to this to another thread is dangerous, as the checks are not performed in
150 //@ a thread-safe manner. However, sending the *entire* `RefCell` is okay, because there's only ever one owner, and all
151 //@ we need to ensure is that everybody attempting to borrow is in the same thread as the owner. <br/>
152 //@ [`Cell<T>`](http://doc.rust-lang.org/beta/std/cell/struct.Cell.html) is like a stripped-down version of `RefCell<T>`: It doesn't allow
153 //@ you to borrow its content. Instead, it has a methods `get` and `set` to change the value stored in the cell, and to copy it out.
154 //@ For obvious reasons, this requires `T` to be `Copy`.
156 //@ You can also think about all these types coming from the other end: Starting with `Cell`, we have a primitive for
157 //@ interior mutability that provides `get` and `set`, both just requiring a shared borrow. Think of these functions as
158 //@ mutating the *content* of the cell, but not the cell itself, the container. (Just like in ML, where assignment to a
159 //@ `ref` changes the content, not the location.) However, due to the ownership discipline, `Cell` only works for types
160 //@ that are `Copy`. Hence we also have `RefCell`, which allows working with the data right in the cell, rather than
161 //@ having to copy it out. `RefCell` uses non-atomic operations for this purpose, so for the multi-threaded setting, there's
162 //@ the thread-safe `RwLock`. And finally, in case a distinction between readers and writers is not helpful, one can use the
163 //@ more efficient `Mutex`.
166 //@ [index](main.html) | [previous](part14.html) | [next](main.html)