From: Ralf Jung Date: Sat, 18 Jul 2015 18:17:18 +0000 (+0200) Subject: tweak parts 11-15 again X-Git-Url: https://git.ralfj.de/rust-101.git/commitdiff_plain/5baae0ea037ed642b7fe8975fb3004b29827d5b1?hp=--cc tweak parts 11-15 again --- 5baae0ea037ed642b7fe8975fb3004b29827d5b1 diff --git a/solutions/src/counter.rs b/solutions/src/counter.rs index afea9d0..319058e 100644 --- a/solutions/src/counter.rs +++ b/solutions/src/counter.rs @@ -11,19 +11,19 @@ impl ConcurrentCounter { } pub fn increment(&self, by: usize) { - let mut counter = self.0.write().unwrap(); + let mut counter = self.0.write().unwrap_or_else(|e| e.into_inner()); *counter = *counter + by; } pub fn compare_and_inc(&self, test: usize, by: usize) { - let mut counter = self.0.write().unwrap(); + let mut counter = self.0.write().unwrap_or_else(|e| e.into_inner()); if *counter == test { *counter += by; } } pub fn get(&self) -> usize { - let counter = self.0.read().unwrap(); + let counter = self.0.read().unwrap_or_else(|e| e.into_inner()); *counter } } diff --git a/src/main.rs b/src/main.rs index 1111443..1317856 100644 --- a/src/main.rs +++ b/src/main.rs @@ -84,7 +84,7 @@ // * [Part 12: Rc, Interior Mutability, Cell, RefCell](part12.html) // * [Part 13: Concurrency, Arc, Send](part13.html) // * [Part 14: Slices, Arrays, External Dependencies](part14.html) -// * [Part 15: Mutex, Interior Mutability (cont.), Sync](part15.html) +// * [Part 15: Mutex, Interior Mutability (cont.), RwLock, Sync](part15.html) // * (to be continued) // #![allow(dead_code, unused_imports, unused_variables, unused_mut, unreachable_code)] diff --git a/src/part11.rs b/src/part11.rs index 5cc1462..9d093e3 100644 --- a/src/part11.rs +++ b/src/part11.rs @@ -42,7 +42,7 @@ impl Callbacks { // Registration simply stores the callback. pub fn register(&mut self, callback: Box) { - self.callbacks.push(callback); /*@*/ + self.callbacks.push(callback); } // We can also write a generic version of `register`, such that it will be instantiated with some concrete closure type `F` diff --git a/src/part12.rs b/src/part12.rs index c749865..40d9ad5 100644 --- a/src/part12.rs +++ b/src/part12.rs @@ -26,7 +26,7 @@ struct Callbacks { impl Callbacks { pub fn new() -> Self { - Callbacks { callbacks: Vec::new() } /*@*/ + Callbacks { callbacks: Vec::new() } } // Registration works just like last time, except that we are creating an `Rc` now. @@ -37,7 +37,7 @@ impl Callbacks { pub fn call(&self, val: i32) { // We only need a shared iterator here. Since `Rc` is a smart pointer, we can directly call the callback. for callback in self.callbacks.iter() { - callback(val); /*@*/ + callback(val); /*@*/ } } } @@ -108,11 +108,11 @@ struct CallbacksMut { impl CallbacksMut { pub fn new() -> Self { - CallbacksMut { callbacks: Vec::new() } /*@*/ + CallbacksMut { callbacks: Vec::new() } } pub fn register(&mut self, callback: F) { - let cell = Rc::new(RefCell::new(callback)); + let cell = Rc::new(RefCell::new(callback)); /*@*/ self.callbacks.push(cell); /*@*/ } diff --git a/src/part13.rs b/src/part13.rs index 76d7154..9f42b82 100644 --- a/src/part13.rs +++ b/src/part13.rs @@ -7,10 +7,10 @@ use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use std::sync::Arc; //@ Our next stop are the concurrency features of Rust. We are going to write our own small version of "grep", -//@ called *rgrep*, and it is going to make use of concurrency: One thread reads the input files, one thread does +//@ called *rgrep*, and it is going to perform three jobs concurrently: One thread reads the input files, one thread does //@ the actual matching, and one thread writes the output. I already mentioned in the beginning of the course that //@ Rust's type system (more precisely, the discipline of ownership and borrowing) will help us to avoid a common -//@ pitfall of concurrent programming: data races. +//@ pitfall of concurrent programming: data races. We will see how that works concretely. // Before we come to the actual code, we define a data-structure `Options` to store all the information we need // to complete the job: Which files to work on, which pattern to look for, and how to output.
@@ -145,7 +145,7 @@ pub fn main() { run(options); } -// **Exercise 12.1**: Change rgrep such that it prints not only the matching lines, but also the name of the file +// **Exercise 13.1**: Change rgrep such that it prints not only the matching lines, but also the name of the file // and the number of the line in the file. You will have to change the type of the channels from `String` to something // that records this extra information. @@ -163,7 +163,7 @@ pub fn main() { //@ still be around. After it sent the string to the other side, `read_files` has no pointer into the string content //@ anymore, and hence no way to race on the data with someone else. //@ -//@ There is a little more to this. Remember the `'static` bound we had to add to `register` in the previous part, to make +//@ There is a little more to this. Remember the `'static` bound we had to add to `register` in the previous parts, to make //@ sure that the callbacks do not reference any pointers that might become invalid? This is just as crucial for spawning //@ a thread: In general, that thread could last for much longer than the current stack frame. Thus, it must not use //@ any pointers to data in that stack frame. This is achieved by requiring the `FnOnce` closure passed to `thread::spawn` @@ -179,9 +179,10 @@ pub fn main() { //@ //@ The answer is already hinted at in the error: It will say something about `Send`. You may have noticed that the closure in //@ `thread::spawn` does not just have a `'static` bound, but also has to satisfy `Send`. `Send` is a trait, and just like `Copy`, -//@ it's just a marker - there are no functions provided by `Send`. What the trait says is that types which are `Send`, can be +//@ it's just a marker - there are no functions provided by `Send`. What the trait says is that types which are `Send` can be //@ safely sent to another thread without causing trouble. Of course, all the primitive data-types are `Send`. So is `Arc`, -//@ which is why Rust accepted our code. But `Rc` is not `Send`, and for a good reason! +//@ which is why Rust accepted our code. But `Rc` is not `Send`, and for a good reason! If had two `Rc` to the same data, and +//@ sent one of them to another thread, things could go havoc due to the lack of synchronization. //@ //@ Now, `Send` as a trait is fairly special. It has a so-called *default implementation*. This means that *every type* implements //@ `Send`, unless it opts out. Opting out is viral: If your type contains a type that opted out, then you don't have `Send`, either. diff --git a/src/part14.rs b/src/part14.rs index 6550fe5..eb2011a 100644 --- a/src/part14.rs +++ b/src/part14.rs @@ -27,7 +27,7 @@ pub fn sort(data: &mut [T]) { /* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot; [rpos,len) is >= pivot; lpos < rpos */ loop { - // **Exercise 13.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a + // **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a // test function for `sort`. unimplemented!() } @@ -47,8 +47,8 @@ pub fn sort(data: &mut [T]) { sort(part2); /*@*/ } -// **Exercise 13.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part -// to call the sort function above. If you did exercise 12.1, you will have slightly more work. Make sure you sort by the matched line +// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part +// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line // only, not by filename or line number! // Now, we can sort, e.g., an vector of numbers. @@ -82,7 +82,7 @@ fn sort_array() { //@ arguments based on the usage string. External dependencies are declared in the `Cargo.toml` file. //@ I already prepared that file, but the declaration of the dependency is still commented out. So please open `Cargo.toml` of your workspace -//@ now, and enabled the two commented-out lines. Then do `cargo build`. Cargo will now download the crate from crates.io, compile it, +//@ now, and enable the two commented-out lines. Then do `cargo build`. Cargo will now download the crate from crates.io, compile it, //@ and link it to your program. In the future, you can do `cargo update` to make it download new versions of crates you depend on. //@ Note that crates.io is only the default location for dependencies, you can also give it the URL of a git repository or some local //@ path. All of this is explained in the [Cargo Guide](http://doc.crates.io/guide.html). @@ -91,7 +91,8 @@ fn sort_array() { // Remove the attribute of the `rgrep` module to enable compilation. #[cfg(feature = "disabled")] pub mod rgrep { - // Now that `docopt` is linked, we can first add it to the namespace and then import shorter names with `use`. We also import some other pieces that we will need. + // Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`. + // We also import some other pieces that we will need. extern crate docopt; use self::docopt::Docopt; use part12::{run, Options, OutputMode}; @@ -108,7 +109,7 @@ Options: // This function extracts the rgrep options from the command-line arguments. fn get_options() -> Options { - // Parse `argv` and exit the program with an error message if it fails. This is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). + // This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/).
//@ The function `and_then` takes a closure from `T` to `Result`, and uses it to transform a `Result` to a //@ `Result`. This way, we can chain computations that only happen if the previous one succeeded (and the error //@ type has to stay the same). In case you know about monads, this style of programming will be familiar to you. @@ -153,7 +154,7 @@ Options: } } -// **Exercise 13.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular +// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular // expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch // the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site. // (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.) diff --git a/src/part15.rs b/src/part15.rs index a783689..9ae5aaf 100644 --- a/src/part15.rs +++ b/src/part15.rs @@ -1,20 +1,23 @@ -// Rust-101, Part 15: Mutex, Interior Mutability (cont.), Sync -// =========================================================== +// Rust-101, Part 15: Mutex, Interior Mutability (cont.), RwLock, Sync +// =================================================================== use std::sync::{Arc, Mutex}; use std::thread; //@ We already saw that we can use `Arc` to share memory between threads. However, `Arc` can only provide *read-only* -//@ access to memory: Since there is aliasing, Rust cannot, in general, permit mutation. If however, -//@ some care would be taken at run-time, then mutation would still be all right: We have to ensure that whenever -//@ someone changes the data, nobody else is looking at it. In other words, we need a *critical section* or (as it -//@ 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*. +//@ access to memory: Since there is aliasing, Rust cannot, in general, permit mutation. To implement shared-memory +//@ concurrency, we need to have aliasing and permutation - following, of course, some strict rules to make sure +//@ there are no data races. In Rust, shared-memory concurrency is obtained through *interior mutability*, +//@ which we already discussed in a single-threaded context in part 12. //@ -//@ As an example, let us write a concurrent counter. As usual in Rust, we first have to think about our data layout. -//@ In case of the mutex, this means we have to declare the type of the data that we want to be protected. In Rust, -//@ a `Mutex` protects data, not code - and it is impossible to access the data in any other way. This is generally considered -//@ good style, but other languages typically lack the ability to actually enforce this. -//@ Of course, we want multiple threads to have access to this `Mutex`, so we wrap it in an `Arc`. +//@ The most basic type for interior mutability that supports concurrency is [`Mutex`](http://doc.rust-lang.org/stable/std/sync/struct.Mutex.html). +//@ This type implements *critical sections* (or *locks*), but in a data-driven way: One has to specify +//@ the type of the data that's protected by the mutex, and Rust ensures that the data is *only* accessed +//@ through the mutex. In other words, "lock data, not code" is actually enforced by the type system, which +//@ becomes possible because of the discipline of ownership and borrowing. +//@ +//@ As an example, let us write a concurrent counter. As usual in Rust, we first have to think about our data layout: +//@ That will be `Mutex`. Of course, we want multiple threads to have access to this `Mutex`, so we wrap it in an `Arc`. //@ //@ Rather than giving every field a name, a struct can also be defined by just giving a sequence of types (similar //@ to how a variant of an `enum` is defined). This is called a *tuple struct*. It is often used when constructing @@ -32,26 +35,12 @@ impl ConcurrentCounter { ConcurrentCounter(Arc::new(Mutex::new(val))) /*@*/ } - //@ The core operation is, of course, `increment`. The type may be surprising at first: A shared borrow? - //@ How can this be, since `increment` definitely modifies the counter? We already discussed above that `Mutex` is - //@ a way to get around this restriction in Rust. This phenomenon of data that can be mutated through a shared - //@ borrow is called *interior mutability*: We are changing the inner parts of the object, but seen from the outside, - //@ this does not count as "mutation". This stands in contrast to *exterior mutability*, which is the kind of - //@ mutability we saw so far, where one piece of data is replaced by something else of the same type. If you are familiar - //@ with languages like ML, you can compare this to how something of type `ref` permits mutation, even though it is - //@ itself a functional value (more precisely, a location) like all the others. - //@ - //@ Interior mutability breaks the rules of Rust that I outlined earlier: There is aliasing (a shared borrow) and mutation. - //@ The reason that this still works is careful programming of the primitives for interior mutability - in this case, that's - //@ `Mutex`. It has to ensure with dynamic checks, at run-time, that things don't fall apart. In particular, it has to ensure - //@ that the data covered by the mutex can only ever be accessed from inside a critical section. This is where Rust's type - //@ system comes into play: With its discipline of ownership and borrowing, it can enforce such rules. Let's see how this goes. + // The core operation is, of course, `increment`. pub fn increment(&self, by: usize) { - // `lock` on a mutex returns a *guard*, giving access to the data contained in the mutex. - //@ (We will discuss the `unwrap` soon.) `.0` is how we access the first component of a tuple or a struct. + // `lock` on a mutex returns a guard, very much like `RefCell`. The guard gives access to the data contained in the mutex. + //@ (We will discuss the `unwrap` soon.) `.0` is how we access the first component of a tuple or a struct. let mut counter = self.0.lock().unwrap(); - //@ The guard is another example of a smart pointer, and it can be used as if it were a pointer to the data protected - //@ by the lock. + //@ The guard is a smart pointer to the content. *counter = *counter + by; //@ At the end of the function, `counter` is dropped and the mutex is available again. //@ This can only happen when full ownership of the guard is given up. In particular, it is impossible for us @@ -106,16 +95,28 @@ pub fn main() { println!("Final value: {}", counter.get()); } -// **Exercise 14.1**: Besides `Mutex`, there's also [`RwLock`](http://doc.rust-lang.org/stable/std/sync/struct.RwLock.html), which -// provides two ways of locking: One that grants only read-only access, to any number of concurrent readers, and another one -// for exclusive write access. (Notice that this is the same pattern we already saw with shared vs. mutable borrows.) Change -// the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time. -// -// **Exercise 14.2**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by +// **Exercise 15.1**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by // `by` *only if* the current value is `test`. +// +// **Exercise 15.2**: Rather than panicking in case the lock is poisoned, we can use `into_innter` on the error to recover +// the data inside the lock. Change the code above to do that. Try using `unwrap_or_else` for this job. + +//@ ## `RwLock` +//@ Besides `Mutex`, there's also [`RwLock`](http://doc.rust-lang.org/stable/std/sync/struct.RwLock.html), which +//@ provides two ways of locking: One that grants only read-only access, to any number of concurrent readers, and another one +//@ for exclusive write access. Notice that this is the same pattern we already saw with shared vs. mutable borrows. Hence +//@ another way of explaining `RwLock` is to say that it is like `RefCell`, but works even for concurrent access. Rather than +//@ panicking when the data is already borrowed, `RwLock` will of course block the current thread until the lock is available. +//@ In this view, `Mutex` is a stripped-down version of `RwLock` that does not distinguish readers and writers. + +// **Exercise 15.3**: Change the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time. //@ ## Sync -//@ In part 12, we talked about types that are marked `Send` and thus can be moved to another thread. However, we did *not* +//@ Clearly, if we had used `RefCell` rather than `Mutex`, the code above could not work: `RefCell` is not prepared for +//@ multiple threads trying to access the data at the same time. How does Rust make sure that we don't accidentally use +//@ `RefCell` across multiple threads? +//@ +//@ In part 13, we talked about types that are marked `Send` and thus can be moved to another thread. However, we did *not* //@ talk about the question whether a borrow is `Send`. For `&mut T`, the answer is: It is `Send` whenever `T` is send. //@ `&mut` allows moving values back and forth, it is even possible to [`swap`](http://doc.rust-lang.org/beta/std/mem/fn.swap.html) //@ the contents of two mutably borrowed values. So in terms of concurrency, sending a mutable borrow is very much like @@ -124,43 +125,22 @@ pub fn main() { //@ But what about `&T`, a shared borrow? Without interior mutability, it would always be all-right to send such values. //@ After all, no mutation can be performed, so there can be as many threads accessing the data as we like. In the //@ presence of interior mutability though, the story gets more complicated. Rust introduces another marker trait for -//@ this purpose: `Sync`. A type `T` is `Sync` if `&T` is `Send`. Just like `Send`, `Sync` has a default implementation +//@ this purpose: `Sync`. A type `T` is `Sync` if and only if `&T` is `Send`. Just like `Send`, `Sync` has a default implementation //@ and is thus automatically implemented for a data-structure *if* all its members implement it. //@ +//@ Since `Arc` provides multiple threads with a shared borrow of its content, `Arc` is only `Send` if `T` is `Sync`. +//@ So if we had used `RefCell` above, which is *not* `Sync`, Rust would have caught that mistake. Notice however that +//@ `RefCell` *is* `Send`: If ownership of the entire cell is moved to another thread, it is still not possible for several +//@ threads to try to access the data at the same time. +//@ //@ Almost all the types we saw so far are `Sync`, with the exception of `Rc`. Remember that a shared borrow is good enough //@ for cloning, and we don't want other threads to clone our local `Rc`, so it must not be `Sync`. The rule of `Mutex` //@ is to enforce synchronization, so it should not be entirely surprising that `Mutex` is `Send` *and* `Sync` provided that //@ `T` is `Send`. //@ -//@ In the next part, we will learn about a type called `RefCell` that is `Send`, but not `Sync`. -//@ //@ You may be curious whether there is a type that's `Sync`, but not `Send`. There are indeed rather esoteric examples //@ of such types, but that's not a topic I want to go into. In case you are curious, there's a //@ [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`. //@ 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. -// FIXME TODO some old outdated explanation FIXME TODO - -//@ [`RefCell`](http://doc.rust-lang.org/beta/std/cell/struct.RefCell.html) -//@ [`is very much like `RwLock`, but it's not thread-safe: "Locking" is done without atomic operations. -//@ One can also see it as a dynamically checked version of Rust's usual borrowing rules. You have to explicitly say -//@ when you want to borrow the data in there shared, or mutably, and Rust will complain at run-time if you have -//@ a mutable borrow while any other borrow is active. You can then write programs that Rust may otherwise not -//@ accept. Sending a shared borrow to this to another thread is dangerous, as the checks are not performed in -//@ a thread-safe manner. However, sending the *entire* `RefCell` is okay, because there's only ever one owner, and all -//@ we need to ensure is that everybody attempting to borrow is in the same thread as the owner.
-//@ [`Cell`](http://doc.rust-lang.org/beta/std/cell/struct.Cell.html) is like a stripped-down version of `RefCell`: It doesn't allow -//@ 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. -//@ For obvious reasons, this requires `T` to be `Copy`. -//@ -//@ You can also think about all these types coming from the other end: Starting with `Cell`, we have a primitive for -//@ interior mutability that provides `get` and `set`, both just requiring a shared borrow. Think of these functions as -//@ mutating the *content* of the cell, but not the cell itself, the container. (Just like in ML, where assignment to a -//@ `ref` changes the content, not the location.) However, due to the ownership discipline, `Cell` only works for types -//@ that are `Copy`. Hence we also have `RefCell`, which allows working with the data right in the cell, rather than -//@ having to copy it out. `RefCell` uses non-atomic operations for this purpose, so for the multi-threaded setting, there's -//@ the thread-safe `RwLock`. And finally, in case a distinction between readers and writers is not helpful, one can use the -//@ more efficient `Mutex`. - - //@ [index](main.html) | [previous](part14.html) | [next](main.html) diff --git a/workspace/src/part11.rs b/workspace/src/part11.rs index ac19371..746aed9 100644 --- a/workspace/src/part11.rs +++ b/workspace/src/part11.rs @@ -23,7 +23,7 @@ impl Callbacks { // Registration simply stores the callback. pub fn register(&mut self, callback: Box) { - unimplemented!() + self.callbacks.push(callback); } // We can also write a generic version of `register`, such that it will be instantiated with some concrete closure type `F` diff --git a/workspace/src/part12.rs b/workspace/src/part12.rs index a351995..23db4f6 100644 --- a/workspace/src/part12.rs +++ b/workspace/src/part12.rs @@ -13,7 +13,7 @@ struct Callbacks { impl Callbacks { pub fn new() -> Self { - unimplemented!() + Callbacks { callbacks: Vec::new() } } // Registration works just like last time, except that we are creating an `Rc` now. @@ -69,11 +69,10 @@ struct CallbacksMut { impl CallbacksMut { pub fn new() -> Self { - unimplemented!() + CallbacksMut { callbacks: Vec::new() } } pub fn register(&mut self, callback: F) { - let cell = Rc::new(RefCell::new(callback)); unimplemented!() } diff --git a/workspace/src/part13.rs b/workspace/src/part13.rs index 501fb7d..ae12cd1 100644 --- a/workspace/src/part13.rs +++ b/workspace/src/part13.rs @@ -120,7 +120,7 @@ pub fn main() { run(options); } -// **Exercise 12.1**: Change rgrep such that it prints not only the matching lines, but also the name of the file +// **Exercise 13.1**: Change rgrep such that it prints not only the matching lines, but also the name of the file // and the number of the line in the file. You will have to change the type of the channels from `String` to something // that records this extra information. diff --git a/workspace/src/part14.rs b/workspace/src/part14.rs index 6e007aa..fb580f9 100644 --- a/workspace/src/part14.rs +++ b/workspace/src/part14.rs @@ -14,7 +14,7 @@ pub fn sort(data: &mut [T]) { /* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot; [rpos,len) is >= pivot; lpos < rpos */ loop { - // **Exercise 13.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a + // **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a // test function for `sort`. unimplemented!() } @@ -27,8 +27,8 @@ pub fn sort(data: &mut [T]) { unimplemented!() } -// **Exercise 13.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part -// to call the sort function above. If you did exercise 12.1, you will have slightly more work. Make sure you sort by the matched line +// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part +// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line // only, not by filename or line number! // Now, we can sort, e.g., an vector of numbers. @@ -49,7 +49,8 @@ fn sort_array() { // Remove the attribute of the `rgrep` module to enable compilation. #[cfg(feature = "disabled")] pub mod rgrep { - // Now that `docopt` is linked, we can first add it to the namespace and then import shorter names with `use`. We also import some other pieces that we will need. + // Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`. + // We also import some other pieces that we will need. extern crate docopt; use self::docopt::Docopt; use part12::{run, Options, OutputMode}; @@ -66,7 +67,7 @@ Options: // This function extracts the rgrep options from the command-line arguments. fn get_options() -> Options { - // Parse `argv` and exit the program with an error message if it fails. This is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). + // This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/).
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit()); // Now we can get all the values out. let count = args.get_bool("-c"); @@ -100,7 +101,7 @@ Options: } } -// **Exercise 13.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular +// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular // expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch // the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site. // (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.) diff --git a/workspace/src/part15.rs b/workspace/src/part15.rs index d006b23..1a6873e 100644 --- a/workspace/src/part15.rs +++ b/workspace/src/part15.rs @@ -1,5 +1,5 @@ -// Rust-101, Part 15: Mutex, Interior Mutability (cont.), Sync -// =========================================================== +// Rust-101, Part 15: Mutex, Interior Mutability (cont.), RwLock, Sync +// =================================================================== use std::sync::{Arc, Mutex}; use std::thread; @@ -15,8 +15,9 @@ impl ConcurrentCounter { unimplemented!() } + // The core operation is, of course, `increment`. pub fn increment(&self, by: usize) { - // `lock` on a mutex returns a *guard*, giving access to the data contained in the mutex. + // `lock` on a mutex returns a guard, very much like `RefCell`. The guard gives access to the data contained in the mutex. let mut counter = self.0.lock().unwrap(); *counter = *counter + by; } @@ -61,16 +62,13 @@ pub fn main() { println!("Final value: {}", counter.get()); } -// **Exercise 14.1**: Besides `Mutex`, there's also [`RwLock`](http://doc.rust-lang.org/stable/std/sync/struct.RwLock.html), which -// provides two ways of locking: One that grants only read-only access, to any number of concurrent readers, and another one -// for exclusive write access. (Notice that this is the same pattern we already saw with shared vs. mutable borrows.) Change -// the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time. -// -// **Exercise 14.2**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by +// **Exercise 15.1**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by // `by` *only if* the current value is `test`. +// +// **Exercise 15.2**: Rather than panicking in case the lock is poisoned, we can use `into_innter` on the error to recover +// the data inside the lock. Change the code above to do that. Try using `unwrap_or_else` for this job. -// FIXME TODO some old outdated explanation FIXME TODO - +// **Exercise 15.3**: Change the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time.