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