first draft of it all

This commit is contained in:
Steve Klabnik
2017-02-23 13:10:51 -05:00
parent 1b8ea15349
commit 36ee5cd0bc
5 changed files with 667 additions and 392 deletions
+4 -1
View File
@@ -80,7 +80,10 @@
- [Smart Pointers](ch15-00-smart-pointers.md)
- [Concurrency](ch16-00-concurrency.md)
- [Fearless Concurrency](ch16-00-concurrency.md)
- [Message Passing](ch16-01-message-passing.md)
- [Shared State](ch16-02-shared-state.md)
- [Extensible Concurrency: `Sync` and `Send`](ch16-03-extensible-concurrency-sync-and-send.md)
- [Is Rust OOP?](ch17-00-oop.md)
+37 -391
View File
@@ -1,393 +1,39 @@
# Fearless Concurrency
The Rust project was initiated to solve two thorny problems:
* How do you do safe systems programming?
* How do you make concurrency painless?
Initially these problems seemed orthogonal, but to our amazement, the
solution turned out to be identical: **the same tools that make Rust
safe also help you tackle concurrency head-on**.
Memory safety bugs and concurrency bugs often come down to code
accessing data when it shouldn't. Rust's secret weapon is *ownership*,
a discipline for access control that systems programmers try to
follow, but that Rust's compiler checks statically for you.
For memory safety, this means you can program without a garbage
collector *and* without fear of segfaults, because Rust will catch
your mistakes.
For concurrency, this means you can choose from a wide variety of
paradigms (message passing, shared state, lock-free, purely
functional), and Rust will help you avoid common pitfalls.
Here's a taste of concurrency in Rust:
* A [channel][mpsc] transfers ownership of the messages sent along it,
so you can send a pointer from one thread to another without fear of
the threads later racing for access through that pointer. **Rust's
channels enforce thread isolation.**
* A [lock][mutex] knows what data it protects, and Rust guarantees
that the data can only be accessed when the lock is held. State is
never accidentally shared. **"Lock data, not code" is enforced in
Rust.**
* Every data type knows whether it can safely be [sent][send] between
or [accessed][sync] by multiple threads, and Rust enforces this safe
usage; there are no data races, even for lock-free data structures.
**Thread safety isn't just documentation; it's law.**
* You can even [share stack frames][scoped] between threads, and Rust
will statically ensure that the frames remain active while other
threads are using them. **Even the most daring forms of sharing are
guaranteed safe in Rust**.
All of these benefits come out of Rust's ownership model, and in fact
locks, channels, lock-free data structures and so on are defined in
libraries, not the core language. That means that Rust's approach to
concurrency is *open ended*: new libraries can embrace new paradigms
and catch new bugs, just by adding APIs that use Rust's ownership
features.
The goal of this post is to give you some idea of how that's done.
### Message passing
Now that we've covered the basic ownership story in Rust, let's see
what it means for concurrency.
Concurrent programming comes in many styles, but a particularly simple
one is message passing, where threads or actors communicate by sending
each other messages. Proponents of the style emphasize the way that
it ties together sharing and communication:
> Do not communicate by sharing memory; instead, share memory by
> communicating.
>
> --[Effective Go](http://golang.org/doc/effective_go.html)
**Rust's ownership makes it easy to turn that advice into a
compiler-checked rule**. Consider the following channel API
([channels in Rust's standard library][mpsc] are a bit different):
~~~~rust
fn send<T: Send>(chan: &Channel<T>, t: T);
fn recv<T: Send>(chan: &Channel<T>) -> T;
~~~~
Channels are generic over the type of data they transmit (the `<T:
Send>` part of the API). The `Send` part means that `T` must be
considered safe to send between threads; we'll come back to that later
in the post, but for now it's enough to know that `Vec<i32>` is
`Send`.
As always in Rust, passing in a `T` to the `send` function means
transferring ownership of it. This fact has profound consequences: it
means that code like the following will generate a compiler error.
~~~~rust
// Suppose chan: Channel<Vec<i32>>
let mut vec = Vec::new();
// do some computation
send(&chan, vec);
print_vec(&vec);
~~~~
Here, the thread creates a vector, sends it to another thread, and
then continues using it. The thread receiving the vector could mutate
it as this thread continues running, so the call to `print_vec` could
lead to race condition or, for that matter, a use-after-free bug.
Instead, the Rust compiler will produce an error message on the call
to `print_vec`:
~~~~
Error: use of moved value `vec`
~~~~
Disaster averted.
### Locks
Another way to deal with concurrency is by having threads communicate
through passive, shared state.
Shared-state concurrency has a bad rap. It's easy to forget to acquire
a lock, or otherwise mutate the wrong data at the wrong time, with
disastrous results -- so easy that many eschew the style altogether.
Rust's take is that:
1. Shared-state concurrency is nevertheless a fundamental programming
style, needed for systems code, for maximal performance, and for
implementing other styles of concurrency.
2. The problem is really about *accidentally* shared state.
Rust aims to give you the tools to conquer shared-state concurrency
directly, whether you're using locking or lock-free techniques.
In Rust, threads are "isolated" from each other automatically, due to
ownership. Writes can only happen when the thread has mutable access,
either by owning the data, or by having a mutable borrow of it. Either
way, **the thread is guaranteed to be the only one with access at the
time**. To see how this plays out, let's look at locks.
Remember that mutable borrows cannot occur simultaneously with other
borrows. Locks provide the same guarantee ("mutual exclusion") through
synchronization at runtime. That leads to a locking API that hooks
directly into Rust's ownership system.
Here is a simplified version (the [standard library's][mutex]
is more ergonomic):
~~~~rust
// create a new mutex
fn mutex<T: Send>(t: T) -> Mutex<T>;
// acquire the lock
fn lock<T: Send>(mutex: &Mutex<T>) -> MutexGuard<T>;
// access the data protected by the lock
fn access<T: Send>(guard: &mut MutexGuard<T>) -> &mut T;
~~~~
This lock API is unusual in several respects.
First, the `Mutex` type is generic over a type `T` of **the data
protected by the lock**. When you create a `Mutex`, you transfer
ownership of that data *into* the mutex, immediately giving up access
to it. (Locks are unlocked when they are first created.)
Later, you can `lock` to block the thread until the lock is
acquired. This function, too, is unusual in providing a return value,
`MutexGuard<T>`. The `MutexGuard` automatically releases the lock when
it is destroyed; there is no separate `unlock` function.
The only way to access the lock is through the `access` function,
which turns a mutable borrow of the guard into a mutable borrow of the
data (with a shorter lease):
~~~~rust
fn use_lock(mutex: &Mutex<Vec<i32>>) {
// acquire the lock, taking ownership of a guard;
// the lock is held for the rest of the scope
let mut guard = lock(mutex);
// access the data by mutably borrowing the guard
let vec = access(&mut guard);
// vec has type `&mut Vec<i32>`
vec.push(3);
// lock automatically released here, when `guard` is destroyed
}
~~~~
There are two key ingredients here:
* The mutable reference returned by `access` cannot outlive the
`MutexGuard` it is borrowing from.
* The lock is only released when the `MutexGuard` is destroyed.
The result is that **Rust enforces locking discipline: it will not let
you access lock-protected data except when holding the lock**. Any
attempt to do otherwise will generate a compiler error. For example,
consider the following buggy "refactoring":
~~~~rust
fn use_lock(mutex: &Mutex<Vec<i32>>) {
let vec = {
// acquire the lock
let mut guard = lock(mutex);
// attempt to return a borrow of the data
access(&mut guard)
// guard is destroyed here, releasing the lock
};
// attempt to access the data outside of the lock.
vec.push(3);
}
~~~~
Rust will generate an error pinpointing the problem:
~~~~
error: `guard` does not live long enough
access(&mut guard)
^~~~~
~~~~
Disaster averted.
### Thread safety and "Send"
It's typical to distinguish some data types as "thread safe" and
others not. Thread safe data structures use enough internal
synchronization to be safely used by multiple threads concurrently.
For example, Rust ships with two kinds of "smart pointers" for
reference counting:
* `Rc<T>` provides reference counting via normal reads/writes. It is
not thread safe.
* `Arc<T>` provides reference counting via *atomic* operations. It is
thread safe.
The hardware atomic operations used by `Arc` are more expensive than
the vanilla operations used by `Rc`, so it's advantageous to use `Rc`
rather than `Arc`. On the other hand, it's critical that an `Rc<T>`
never migrate from one thread to another, because that could lead to
race conditions that corrupt the count.
Usually, the only recourse is careful documentation; most languages
make no *semantic* distinction between thread-safe and thread-unsafe
types.
In Rust, the world is divided into two kinds of data types: those that
are [`Send`][send], meaning they can be safely moved from one thread to
another, and those that are `!Send`, meaning that it may not be safe
to do so. If all of a type's components are `Send`, so is that type --
which covers most types. Certain base types are not inherently
thread-safe, though, so it's also possible to explicitly mark a type
like `Arc` as `Send`, saying to the compiler: "Trust me; I've verified
the necessary synchronization here."
Naturally, `Arc` is `Send`, and `Rc` is not.
We already saw that the `Channel` and `Mutex` APIs work only with
`Send` data. Since they are the point at which data crosses thread
boundaries, they are also the point of enforcement for `Send`.
Putting this all together, Rust programmers can reap the benefits of
`Rc` and other thread-*unsafe* types with confidence, knowing that if
they ever do accidentally try to send one to another thread, the Rust
compiler will say:
~~~~
`Rc<Vec<i32>>` cannot be sent between threads safely
~~~~
Disaster averted.
### Sharing the stack: "scoped"
_Note: The API mentioned here is an old one which has been moved out of
the standard library. You can find equivalent functionality in
[`crossbeam`][crossbeam-crate] ([documentation for `scope()`][crossbeam-doc])
and [`scoped_threadpool`][scoped-threadpool-crate]
([documentation for `scoped()`][scoped-threadpool-doc])_
So far, all the patterns we've seen involve creating data structures
on the heap that get shared between threads. But what if we wanted to
start some threads that make use of data living in our stack frame?
That could be dangerous:
~~~~rust
fn parent() {
let mut vec = Vec::new();
// fill the vector
thread::spawn(|| {
print_vec(&vec)
})
}
~~~~
The child thread takes a reference to `vec`, which in turn resides in
the stack frame of `parent`. When `parent` exits, the stack frame is
popped, but the child thread is none the wiser. Oops!
To rule out such memory unsafety, Rust's basic thread spawning API
looks a bit like this:
~~~~rust
fn spawn<F>(f: F) where F: 'static, ...
~~~~
The `'static` constraint is a way of saying, roughly, that no borrowed
data is permitted in the closure. It means that a function like
`parent` above will generate an error:
~~~~
error: `vec` does not live long enough
~~~~
essentially catching the possibility of `parent`'s stack frame
popping. Disaster averted.
But there is another way to guarantee safety: ensure that the parent
stack frame stays put until the child thread is done. This is the
pattern of *fork-join* programming, often used for divide-and-conquer
parallel algorithms. Rust supports it by providing a
["scoped"][scoped] variant of thread spawning:
~~~~rust
fn scoped<'a, F>(f: F) -> JoinGuard<'a> where F: 'a, ...
~~~~
There are two key differences from the `spawn` API above:
* The use a parameter `'a`, rather than `'static`. This parameter
represents a scope that encompasses all the borrows within the
closure, `f`.
* The return value, a `JoinGuard`. As its name suggests, `JoinGuard`
ensures that the parent thread joins (waits on) its child, by
performing an implicit join in its destructor (if one hasn't happened
explicitly already).
Including `'a` in `JoinGuard` ensures that the `JoinGuard` **cannot
escape the scope of any data borrowed by the closure**. In other
words, Rust guarantees that the parent thread waits for the child to
finish before popping any stack frames the child might have access to.
Thus by adjusting our previous example, we can fix the bug and satisfy
the compiler:
~~~~rust
fn parent() {
let mut vec = Vec::new();
// fill the vector
let guard = thread::scoped(|| {
print_vec(&vec)
});
// guard destroyed here, implicitly joining
}
~~~~
So in Rust, you can freely borrow stack data into child threads,
confident that the compiler will check for sufficient synchronization.
### Data races
At this point, we've seen enough to venture a strong statement about
Rust's approach to concurrency: **the compiler prevents all *data races*.**
> A data race is any unsynchronized, concurrent access to data
> involving a write.
Synchronization here includes things as low-level as atomic
instructions. Essentially, this is a way of saying that you cannot
accidentally "share state" between threads; all (mutating) access to
state has to be mediated by *some* form of synchronization.
Data races are just one (very important) kind of race condition, but
by preventing them, Rust often helps you prevent other, more subtle
races as well. For example, it's often important that updates to
different locations appear to take place *atomically*: other threads
see either all of the updates, or none of them. In Rust, having `&mut`
access to the relevant locations at the same time **guarantees
atomicity of updates to them**, since no other thread could possibly
have concurrent read access.
It's worth pausing for a moment to think about this guarantee in the
broader landscape of languages. Many languages provide memory safety
through garbage collection. But garbage collection doesn't give you
any help in preventing data races.
While Rust has a strong focus on memory safety, it's more than only that.
There's one problem in particular that's becoming more and more important, yet
many languages are ill-equipped to deal with: concurrency and parallelism.
Rust's goals have always included making concurrent and/or parallel code
easier.
Originally, we thought that these were two separate problems, to be solved with
different methods, but over time, we discovered that ownership provides a
powerful set of tools for dealing with these problems too. In short, many
concurrency and/or parallelism errors are *compile time* errors in Rust,
rather than runtime errors. We've nicknamed this aspect of Rust 'fearless
concurrency', as it not only allows you to have confidence that your code
is free of subtle bugs, but also lets you refactor this kind of code easily,
without worrying about introducing new bugs.
> Side note: given that the slogan is 'fearless concurrency', we'll be
> referring to many of the problems here as 'concurrent' ones rather than
> 'concurrent and/or parallel' ones, for simplicity's sake. These two kinds
> of problems are similar, but technically different. If this were a book
> specifically about concurrency and/or parallelism, we'd be sure to be
> more specific, but for this chapter, we're going to fudge it. Sorry about
> that, pedants!
Many languages that give you tools to deal with concurrent problems are
strongly opinionated about them. That's a very reasonable strategy, but
lower-level languages don't have that luxury. Rust, therefore, gives us
a variety of tools for modelling our problems in whatever way we feel is
appropriate.
Here's what we'll cover in this chapter:
* *Message passing* concurrency, where channels are used to send messages
between threads.
* *Shared state* concurrency, where multiple threads have access to some piece
of data.
* The `Sync` and `Send` traits, which allow Rust's concurrency guarantees to be
*extensible*; they aren't limited to the built-in types.
+333
View File
@@ -0,0 +1,333 @@
# Message Passing
One approach to concurrency that's seen a rise in popularity as of late is
*message passing*, where threads or actors communicate by sending each other
messages. Here's the idea in slogan form:
> Do not communicate by sharing memory; instead, share memory by
> communicating.
>
> --[Effective Go](http://golang.org/doc/effective_go.html)
A major tool to accomplish this goal is the *channel*. Channels look like
this:
```rust
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
tx.send(String::from("Hello!")).unwrap();
println!("{:?}", rx.recv().unwrap());
```
The `mpsc::channel` function crates a new channel. What's up with 'mpsc'?
It stands for "multiple producer, single consumer." In short, you can have
multiple *sending* ends of a channel, but only one *receiving* end.
`mpsc::channel` returns a tuple: the first element is the sending end, the
second element is the receiving end. For historical reasons, many people use
`rx` and `tx` to abbreviate 'transmitter' and 'receiver', and so those are the
names we're using for the variables bound to each end.
The `tx` end has one useful method: `send`. In our example, we send a `String`
down the channel. Doing this returns a `Result<T, E>` type, because if the
receiving end has already been deallocated, there's nowhere to send it to, and
so we'd get an error. In this example, we're simply calling `unwrap` to ignore
this error, but for a real application, we'd want to handle it properly.
Chapter 9 is where you'd go to review strategies for proper error handling.
The `rx` end has two useful methods: `recv` and `try_recv`. 'recv' is short for
'receive'. Here, we're using the former. This method will block execution until
a value is sent down the channel. Once one is, it will return it. The `try_`
variant of `recv` will not block; it instead returns a `Result<T, E>`
immediately.
## Channels and ownership
These basic aspects of channels are the same in every language: send something
down one end, receive it on the other end. Where Rust is special, though, is
ownership. Consider this example, which is slightly modified from the above
one:
```rust,ignore
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
let message = String::from("Hello!");
tx.send(message).unwrap();
println!("Sent {}", message);
println!("{:?}", rx.recv().unwrap());
```
Here, we try to print out `message` after we've sent it down the channel via
`tx.send`. If you try to compile this code, Rust will error:
```text
error[E0382]: use of moved value: `message`
--> <anon>:9:21
|
7 | tx.send(message).unwrap();
| ------- value moved here
8 |
9 | println!("Sent {}", message);
| ^^^^^^^ value used here after move
|
= note: move occurs because `message` has type `std::string::String`, which does not implement the `Copy` trait
```
Our concurrency mistake has caused a compile-time error! `send` takes its
argument by value, and so moves whatever it's passed. This means we can't
accidentally use it again; the ownership system checks that everything is okay.
In this regard, message passing is very similar to single ownership in Rust.
Message passing enthusiasts enjoy it for similar reasons as Rustaceans enjoy
Rust; single ownership means certain classes of problems go away. If only one
thread at a time can own some memory, there's no chance of getting a data race.
## An example
Let's show off a slightly more realistic example. Let's make a thread that
generates numbers. It'll then send the numbers down a channel. The main thread
will receive the numbers and print them out.
Let's start without any threads:
```rust
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
for i in 0..10 {
tx.send(i).unwrap();
}
drop(tx);
for num in rx {
println!("got number: {}", num);
}
}
```
We've already covered `use` statements in previous chapters, and we covered
creating `tx` and `rx` earlier in this chapter. Let's look at the first new
part:
```rust,ignore
for i in 0..10 {
tx1.send(i).unwrap();
}
```
Instead of sending one number, we're sending ten numbers. We've seen loops
before, we've seen the `send` call before, this is putting the two together.
```rust,ignore
drop(tx);
```
Here's the first truly new thing in this example. In the last chapter, we
talked about the `Drop` trait and how it cleans up resources. Well, when we're
done with a channel, the sender's `Drop` implementation notifies any receivers
that we're done sending data. As such, we can use the `drop` function to do
this before the variable goes out of scope. Why can't we simply wait until `tx`
goes out of scope? The key to answering that question is in the last line:
```rust,ignore
for num in rx {
println!("got number: {}", num);
}
```
The receiving end of channels can be used as an iterator. This `for` loop
will keep going until the sending end finishes. If we didn't call `drop`,
we'd be waiting in this loop forever, as `tx` hasn't left scope yet!
Since we've explicitly hung up the sending end, though, this works. Give
it a try:
```bash
$ cargo run
got number: 0
got number: 1
got number: 2
got number: 3
got number: 4
got number: 5
got number: 6
got number: 7
got number: 8
got number: 9
```
Great! Things are working. But this isn't using any concurrency. Let's add
in a thread, and run our number generation inside of it:
```rust
use std::thread;
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for i in 0..10 {
tx.send(i).unwrap();
}
});
for num in rx {
println!("got number: {}", num);
}
}
```
There are two changes here. The first is using `thread::spawn` to create a new
thread. We use a `move` closure to make `tx` move into the closure, which
explains our second difference: we no longer need an explicit `drop` of `tx`.
If we run this example, we should see the same results as before. We've
introduced a thread, but we don't see any evidence that the thread is running
in paralell to the main thread.
We can show that this is happening at the same time with a call
`thread::sleep`:
```rust
use std::thread;
use std::sync::mpsc;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for i in 0..10 {
tx.send(i).unwrap();
thread::sleep(Duration::new(1, 0));
}
});
for num in rx {
println!("got number: {}", num);
}
}
```
The call to `thread::sleep` will make the thread stop executing for the
`Duration` it's been passed. In this case, we've created a duration of one
second. When running this version of the example, you'll see the same output,
but with a one-second pause in between. There's no pausing in our recieving
loop, so we can tell that the main thread is waiting on the secondary thread.
Near the start of this section, we mentioned that 'mpsc' stood for "multiple
producer, single consumer." We can expand our example to show this behavior
off. Check it out:
```rust
use std::thread;
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();
thread::spawn(move || {
for i in 0..10 {
tx1.send(i).unwrap();
}
});
thread::spawn(move || {
for i in 10..20 {
tx.send(i).unwrap();
}
});
for num in rx {
println!("got number: {}", num);
}
}
```
Here, we call `clone` on the sending end of the channel. This will give us a
new sending handle, which we can pass to a new thread. So we create two
threads, pass the two sending ends of the channel to them, and generate
different numbers for each.
If you run this, you'll *probably* see output like this:
```rust
got number: 0
got number: 1
got number: 2
got number: 3
got number: 4
got number: 5
got number: 6
got number: 7
got number: 8
got number: 9
got number: 10
got number: 11
got number: 12
got number: 13
got number: 14
got number: 15
got number: 16
got number: 17
got number: 18
got number: 19
```
You also may see the two-digit numbers first, or you may see them interleaved.
It depends on your system! This is what makes concurrency interesting, but also
difficult. If you play around with `thread::sleep`, giving it different values,
you can make the runs more non-deterministic, and get different output each
time. Here's an example that worked on my computer:
```rust
use std::thread;
use std::sync::mpsc;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();
thread::spawn(move || {
for i in 0..10 {
tx1.send(i).unwrap();
if i % 2 == 0 {
thread::sleep(Duration::new(0, 10));
}
}
});
thread::spawn(move || {
for i in 10..20 {
tx.send(i).unwrap();
if i % 2 == 1 {
thread::sleep(Duration::new(0, 20));
}
}
});
for num in rx {
println!("got number: {}", num);
}
}
```
## Summary
Now that we've seen how channels work, let's look at shared-memory concurrency.
+230
View File
@@ -0,0 +1,230 @@
# Shared state
While message passing is a fine way of dealing with concurrency, it's not the
only one. Consider the slogan again:
> Do not communicate by sharing memory; instead, share memory by
> communicating.
What would "communicate by sharing memory" look like? And moreover, why would
message passing enthusiasts dislike it, and dislike it enough to invert it
entirely?
Remember how channels are sort of like single ownership? Shared memory
concurrency is sort of like multiple ownership: multiple threads can access the
same memory location at the same time. As we saw with ownership, this can add
additional complexity, as we need to manage these different owners somehow.
Ownership can help a lot here, though. For example, let's look at one of the
more common concurrency primitives for shared memory: mutexes.
## Mutexes
A *mutex* is a concurrency primitive for sharing memory. It's short for "mutual
exclusion", that is, it only allows one thread to access some data at any given
time. Mutexes have a reputation as being hard to use, becuase there's a lot you
have to remember:
1. You have to remember to actually attempt to aquire the lock.
2. One you're done with the memory that's being guarded by the mutex, you have
to remember to unlock the memory.
This can be incredibly tricky to get right, and that's why so many are
enthusiastic about channels. However, in Rust, you cannot get these two points
wrong, thanks to our secret power again, ownership. Let's see an example:
```rust
use std::sync::Mutex;
let m = Mutex::new(5);
let mut num = m.lock().unwrap();
*num = 6;
```
Like many types, we create a `Mutex<T>` through a `new` method. To access
the data inside the mutex, we use the `lock` method to aquire the lock. This
call will block until we're able to do so. This call can fail, so similar to
the last section, we use `unwrap()` for now, rather than better error handling.
See Chapter 9 for better tools.
Once we have aquired the lock, we can treat its return value, named `num` in
this case, as a mutable reference to the data inside. This is how the first
problem with mutexes is solved; `Mutex<i32>` is not an `i32`, and so we _must_
aquire the lock in order to use this memory. We can't forget; the type system
won't let us do otherwise.
As you may have suspected, `Mutex<T>` is a smart pointer. Well, more
accurately, the call to `lock` returns a smart pointer, called `MutexGuard`.
This smart pointer implements `Deref` to point at our inner data, similar to
the other smart pointers we saw in the last chapter. In addition, it has a
`Drop` implementation that releases the lock. This is the secret to solving
problem number two with mutexes: we can't forget to release the lock. It
happens for us automatically when the `MutexGuard` goes out of scope.
Let's try to use `Mutex<T>` in an example. We'll spin up ten threads, and have
them each increment a counter. This example won't _quite_ work yet:
```rust,ignore
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0);
let guards: Vec<_> = (0..10).map(|_| {
thread::spawn(|| {
let mut num = counter.lock().unwrap();
*num += 1;
})
}).collect();
for guard in guards {
guard.join().unwrap();
}
println!("Answer: {}", *counter.lock().unwrap());
}
```
Here's the error:
```text
error[E0373]: closure may outlive the current function, but it borrows `**counter`, which is owned by the current function
--> <anon>:8:23
|
8 | thread::spawn(|| {
| ^^ may outlive borrowed value `**counter`
9 | let mut num = counter.lock().unwrap();
| ------- `**counter` is borrowed here
|
help: to force the closure to take ownership of `**counter` (and any other referenced variables), use the `move` keyword, as shown:
| thread::spawn(move || {
```
Given that we spin up multiple threads, Rust can't know how long the threads
will run. As such, we can't borrow the mutex. We need something else. The help
message has a clue: we could use `move` to give ownership to each thread. Let's
try it:
```text
error[E0382]: use of moved value: `counter`
--> <anon>:19:29
|
7 | let guards: Vec<_> = (0..10).map(|_| {
| --- value moved (into closure) here
...
19 | println!("Answer: {}", *counter.lock().unwrap());
| ^^^^^^^ value used here after move
|
= note: move occurs because `counter` has type `std::sync::Mutex<i32>`, which does not implement the `Copy` trait
error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
--> <anon>:8:23
|
8 | thread::spawn(move || {
| ^^^^^^^ cannot move out of captured outer variable in an `FnMut` closure
```
Ouch! That doesn't work either. We can't give away ownership to multiple
threads. We need a different solution. Well, in the last section, we heard
about multiple ownership with `Rc<T>` Let's try that? Here's the code:
```rust,ignore
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Rc::new(Mutex::new(0));
let guards: Vec<_> = (0..10).map(|_| {
let counter = counter.clone();
thread::spawn(|| {
let mut num = counter.lock().unwrap();
*num += 1;
})
}).collect();
for guard in guards {
guard.join().unwrap();
}
println!("Answer: {}", *counter.lock().unwrap());
}
```
This doesn't quite work either. Here's the error:
```text
error[E0277]: the trait bound `std::rc::Rc<std::sync::Mutex<i32>>: std::marker::Sync` is not satisfied
--> <anon>:11:9
|
11 | thread::spawn(|| {
| ^^^^^^^^^^^^^ the trait `std::marker::Sync` is not implemented for `std::rc::Rc<std::sync::Mutex<i32>>`
|
= note: `std::rc::Rc<std::sync::Mutex<i32>>` cannot be shared between threads safely
= note: required because of the requirements on the impl of `std::marker::Send` for `&std::rc::Rc<std::sync::Mutex<i32>>`
= note: required because it appears within the type `[closure@<anon>:11:23: 15:10 counter:&std::rc::Rc<std::sync::Mutex<i32>>]`
= note: required by `std::thread::spawn`
```
... buried in the middle of all of those types is the answer: `Rc<Mutex<i32>>`
cannot be shared between threads safely. Ugh! So close.
Why isn't `Rc<T>` safe to share across threads? Well, if you recall, when we
deal with the reference count, we have to add and subtract for each call to
`clone` and when they go out of scope. This isn't threadsafe, since `Rc<T>`
doesn't use any concurrency primitives to make sure that the count is safe.
This could lead to subtle bugs where the counts are wrong, and we accidentally
leak memory or free it too early. So, what if we had a type that was exactly
like `Rc<T>`, but made these counts thread-safe?
If you thought that question sounded like a leading one, you'd be right. There
is: `Arc<T>`. The 'a' stands for 'atomic', so it's an 'atomically reference
counted' type. Atomics are an additional kind of concurrency primtive that we
won't cover here, see the standard library documentation for `std::atomic` for
more. The gist of it is this: they work like primitive types, but are safe to
share across threads. Why isn't this safety the default? Becuase it comes with
a performance penalty.
Anyway, `Arc<T>` and `Rc<T>` are identical except for the atomic internals. The
API is the same, so we can change our import line, and change our call to
`new`, and now it works:
```rust
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let guards: Vec<_> = (0..10).map(|_| {
let counter = counter.clone();
thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
})
}).collect();
for guard in guards {
guard.join().unwrap();
}
println!("Answer: {}", *counter.lock().unwrap());
}
```
We did it!
You may notice that this means that `Mutex<T>` provides interior mutability,
like the `Cell` family does. In the same way that we use `RefCell<T>` to be
able to mutate contents inside an `Rc<T>`, we use `Mutex<T>` to be able to
mutate contents inside of an `Arc<T>`.
@@ -0,0 +1,63 @@
# Extensible Concurrency with `Sync` and `Send`
One interesting aspect of Rust's concurrency model is that the language knows
_very_ little about concurrency. Almost everything we've been talking about so
far has been part of the standard library, not the language itself:
`std::thread`, `std::sync`, etc. Due to this strategy, we're not limited to the
concurrency options that the standard library or language provide: we can write
our own, or use ones others have written.
We said *almost* everything wasn't in the language, so what is? The answer lies
in the last error message from the previous section:
```text
error[E0277]: the trait bound `std::rc::Rc<std::sync::Mutex<i32>>: std::marker::Sync` is not satisfied
<snip>
= note: required because of the requirements on the impl of `std::marker::Send` for `&std::rc::Rc<std::sync::Mutex<i32>>`
```
That is, there's two traits here, both in `std::marker`: `Sync`, and `Send`.
These two traits define two important properties when it comes to concurrency.
All of the traits in `std::marker` are called "marker traits", and that's
because they don't have any methods. They simply mark a type has having a given
property. As an example:
```rust
// Create our own marker trait as an example:
trait Marker {}
// We implement it for types where it makes sense:
impl Marker for i32 {}
// We can then use it as a bound to a function to only accept types that have
// that property:
fn takes_marker<T: Marker>(t: T) {
// ...
}
```
It's the same for `Send` and `Sync`: they don't add any methods, they only
indicate concurrency properties.
## `Send`
The `Send` marker trait indicates that a type is allowed to have ownership
transferred between threads. Almost every Rust type is `Send`, but there are
still sometimes exceptions. For example, OpenGL, the graphics library, is not
threadsafe in many circumstances. The Rust wrappers for it need to take this
into account. But in pure Rust code, virtually everything is `Send`, so we
won't spend more time on it.
## `Sync`
`Sync`, on the other hand, is more interesting. If your type is `Sync`, it's
safe to access from multiple threads. This is why, when we tried to share our
`Rc<T>` across threads, we got an error: `Rc<T>` is not `Sync`. `Arc<T>`,
however, is, as long as its `T` is also `Sync`. `Mutex<T>` is `Sync`, and so
`Arc<Mutex<T>>` is `Sync`. Non-threadsafe types with interior mutability, like
`RefCell<T>` are not `Sync`, and so `Arc<RefCell<T>>`, for example, would not
be `Sync`.
## Building your own abstractions
Should we include crossbeam here?