| 1 |
# Rayon FAQ |
| 2 |
|
| 3 |
This file is for general questions that don't fit into the README or crate docs. |
| 4 |
|
| 5 |
## How many threads will Rayon spawn? |
| 6 |
|
| 7 |
By default, Rayon uses the same number of threads as the number of CPUs |
| 8 |
available. Note that on systems with hyperthreading enabled this equals the |
| 9 |
number of logical cores and not the physical ones. |
| 10 |
|
| 11 |
If you want to alter the number of threads spawned, you can set the |
| 12 |
environmental variable `RAYON_NUM_THREADS` to the desired number of threads or |
| 13 |
use the |
| 14 |
[`ThreadPoolBuilder::build_global` function](https://docs.rs/rayon/*/rayon/struct.ThreadPoolBuilder.html#method.build_global) |
| 15 |
method. |
| 16 |
|
| 17 |
## How does Rayon balance work between threads? |
| 18 |
|
| 19 |
Behind the scenes, Rayon uses a technique called **work stealing** to try and |
| 20 |
dynamically ascertain how much parallelism is available and exploit it. The idea |
| 21 |
is very simple: we always have a pool of worker threads available, waiting for |
| 22 |
some work to do. When you call `join` the first time, we shift over into that |
| 23 |
pool of threads. But if you call `join(a, b)` from a worker thread W, then W |
| 24 |
will place `b` into its work queue, advertising that this is work that other |
| 25 |
worker threads might help out with. W will then start executing `a`. |
| 26 |
|
| 27 |
While W is busy with `a`, other threads might come along and take `b` from its |
| 28 |
queue. That is called *stealing* `b`. Once `a` is done, W checks whether `b` was |
| 29 |
stolen by another thread and, if not, executes `b` itself. If W runs out of jobs |
| 30 |
in its own queue, it will look through the other threads' queues and try to |
| 31 |
steal work from them. |
| 32 |
|
| 33 |
This technique is not new. It was first introduced by the [Cilk project][cilk], |
| 34 |
done at MIT in the late nineties. The name Rayon is an homage to that work. |
| 35 |
|
| 36 |
[cilk]: http://supertech.csail.mit.edu/cilk/ |
| 37 |
|
| 38 |
## What should I do if I use `Rc`, `Cell`, `RefCell` or other non-Send-and-Sync types? |
| 39 |
|
| 40 |
There are a number of non-threadsafe types in the Rust standard library, and if |
| 41 |
your code is using them, you will not be able to combine it with Rayon. |
| 42 |
Similarly, even if you don't have such types, but you try to have multiple |
| 43 |
closures mutating the same state, you will get compilation errors; for example, |
| 44 |
this function won't work, because both closures access `slice`: |
| 45 |
|
| 46 |
```rust |
| 47 |
/// Increment all values in slice. |
| 48 |
fn increment_all(slice: &mut [i32]) { |
| 49 |
rayon::join(|| process(slice), || process(slice)); |
| 50 |
} |
| 51 |
``` |
| 52 |
|
| 53 |
The correct way to resolve such errors will depend on the case. Some cases are |
| 54 |
easy: for example, uses of [`Rc`] can typically be replaced with [`Arc`], which |
| 55 |
is basically equivalent, but thread-safe. |
| 56 |
|
| 57 |
Code that uses `Cell` or `RefCell`, however, can be somewhat more complicated. |
| 58 |
If you can refactor your code to avoid those types, that is often the best way |
| 59 |
forward, but otherwise, you can try to replace those types with their threadsafe |
| 60 |
equivalents: |
| 61 |
|
| 62 |
- `Cell` -- replacement: `AtomicUsize`, `AtomicBool`, etc |
| 63 |
- `RefCell` -- replacement: `RwLock`, or perhaps `Mutex` |
| 64 |
|
| 65 |
However, you have to be wary! The parallel versions of these types have |
| 66 |
different atomicity guarantees. For example, with a `Cell`, you can increment a |
| 67 |
counter like so: |
| 68 |
|
| 69 |
```rust |
| 70 |
let value = counter.get(); |
| 71 |
counter.set(value + 1); |
| 72 |
``` |
| 73 |
|
| 74 |
But when you use the equivalent `AtomicUsize` methods, you are actually |
| 75 |
introducing a potential race condition (not a data race, technically, but it can |
| 76 |
be an awfully fine distinction): |
| 77 |
|
| 78 |
```rust |
| 79 |
let value = tscounter.load(Ordering::SeqCst); |
| 80 |
tscounter.store(value + 1, Ordering::SeqCst); |
| 81 |
``` |
| 82 |
|
| 83 |
You can already see that the `AtomicUsize` API is a bit more complex, as it |
| 84 |
requires you to specify an |
| 85 |
[ordering](https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html). (I |
| 86 |
won't go into the details on ordering here, but suffice to say that if you don't |
| 87 |
know what an ordering is, and probably even if you do, you should use |
| 88 |
`Ordering::SeqCst`.) The danger in this parallel version of the counter is that |
| 89 |
other threads might be running at the same time and they could cause our counter |
| 90 |
to get out of sync. For example, if we have two threads, then they might both |
| 91 |
execute the "load" before either has a chance to execute the "store": |
| 92 |
|
| 93 |
``` |
| 94 |
Thread 1 Thread 2 |
| 95 |
let value = tscounter.load(Ordering::SeqCst); |
| 96 |
// value = X let value = tscounter.load(Ordering::SeqCst); |
| 97 |
// value = X |
| 98 |
tscounter.store(value+1); tscounter.store(value+1); |
| 99 |
// tscounter = X+1 // tscounter = X+1 |
| 100 |
``` |
| 101 |
|
| 102 |
Now even though we've had two increments, we'll only increase the counter by |
| 103 |
one! Even though we've got no data race, this is still probably not the result |
| 104 |
we wanted. The problem here is that the `Cell` API doesn't make clear the scope |
| 105 |
of a "transaction" -- that is, the set of reads/writes that should occur |
| 106 |
atomically. In this case, we probably wanted the get/set to occur together. |
| 107 |
|
| 108 |
In fact, when using the `Atomic` types, you very rarely want a plain `load` or |
| 109 |
plain `store`. You probably want the more complex operations. A counter, for |
| 110 |
example, would use `fetch_add` to atomically load and increment the value in one |
| 111 |
step. Compare-and-swap is another popular building block. |
| 112 |
|
| 113 |
A similar problem can arise when converting `RefCell` to `RwLock`, but it is |
| 114 |
somewhat less likely, because the `RefCell` API does in fact have a notion of a |
| 115 |
transaction: the scope of the handle returned by `borrow` or `borrow_mut`. So if |
| 116 |
you convert each call to `borrow` to `read` (and `borrow_mut` to `write`), |
| 117 |
things will mostly work fine in a parallel setting, but there can still be |
| 118 |
changes in behavior. Consider using a `handle: RefCell<Vec<i32>>` like: |
| 119 |
|
| 120 |
```rust |
| 121 |
let len = handle.borrow().len(); |
| 122 |
for i in 0 .. len { |
| 123 |
let data = handle.borrow()[i]; |
| 124 |
println!("{}", data); |
| 125 |
} |
| 126 |
``` |
| 127 |
|
| 128 |
In sequential code, we know that this loop is safe. But if we convert this to |
| 129 |
parallel code with an `RwLock`, we do not: this is because another thread could |
| 130 |
come along and do `handle.write().unwrap().pop()`, and thus change the length of |
| 131 |
the vector. In fact, even in *sequential* code, using very small borrow sections |
| 132 |
like this is an anti-pattern: you ought to be enclosing the entire transaction |
| 133 |
together, like so: |
| 134 |
|
| 135 |
```rust |
| 136 |
let vec = handle.borrow(); |
| 137 |
let len = vec.len(); |
| 138 |
for i in 0 .. len { |
| 139 |
let data = vec[i]; |
| 140 |
println!("{}", data); |
| 141 |
} |
| 142 |
``` |
| 143 |
|
| 144 |
Or, even better, using an iterator instead of indexing: |
| 145 |
|
| 146 |
```rust |
| 147 |
let vec = handle.borrow(); |
| 148 |
for data in vec { |
| 149 |
println!("{}", data); |
| 150 |
} |
| 151 |
``` |
| 152 |
|
| 153 |
There are several reasons to prefer one borrow over many. The most obvious is |
| 154 |
that it is more efficient, since each borrow has to perform some safety checks. |
| 155 |
But it's also more reliable: suppose we modified the loop above to not just |
| 156 |
print things out, but also call into a helper function: |
| 157 |
|
| 158 |
```rust |
| 159 |
let vec = handle.borrow(); |
| 160 |
for data in vec { |
| 161 |
helper(...); |
| 162 |
} |
| 163 |
``` |
| 164 |
|
| 165 |
And now suppose, independently, this helper fn evolved and had to pop something |
| 166 |
off of the vector: |
| 167 |
|
| 168 |
```rust |
| 169 |
fn helper(...) { |
| 170 |
handle.borrow_mut().pop(); |
| 171 |
} |
| 172 |
``` |
| 173 |
|
| 174 |
Under the old model, where we did lots of small borrows, this would yield |
| 175 |
precisely the same error that we saw in parallel land using an `RwLock`: the |
| 176 |
length would be out of sync and our indexing would fail (note that in neither |
| 177 |
case would there be an actual *data race* and hence there would never be |
| 178 |
undefined behavior). But now that we use a single borrow, we'll see a borrow |
| 179 |
error instead, which is much easier to diagnose, since it occurs at the point of |
| 180 |
the `borrow_mut`, rather than downstream. Similarly, if we move to an `RwLock`, |
| 181 |
we'll find that the code either deadlocks (if the write is on the same thread as |
| 182 |
the read) or, if the write is on another thread, works just fine. Both of these |
| 183 |
are preferable to random failures in my experience. |
| 184 |
|
| 185 |
## But wait, isn't Rust supposed to free me from this kind of thinking? |
| 186 |
|
| 187 |
You might think that Rust is supposed to mean that you don't have to think about |
| 188 |
atomicity at all. In fact, if you avoid interior mutability (`Cell` and |
| 189 |
`RefCell` in a sequential setting, or `AtomicUsize`, `RwLock`, `Mutex`, et al. |
| 190 |
in parallel code), then this is true: the type system will basically guarantee |
| 191 |
that you don't have to think about atomicity at all. But often there are times |
| 192 |
when you WANT threads to interleave in the ways I showed above. |
| 193 |
|
| 194 |
Consider for example when you are conducting a search in parallel, say to find |
| 195 |
the shortest route. To avoid fruitless search, you might want to keep a cell |
| 196 |
with the shortest route you've found thus far. This way, when you are searching |
| 197 |
down some path that's already longer than this shortest route, you can just stop |
| 198 |
and avoid wasted effort. In sequential land, you might model this "best result" |
| 199 |
as a shared value like `Rc<Cell<usize>>` (here the `usize` represents the length |
| 200 |
of best path found so far); in parallel land, you'd use a `Arc<AtomicUsize>`. |
| 201 |
|
| 202 |
```rust |
| 203 |
fn search(path: &Path, cost_so_far: usize, best_cost: &AtomicUsize) { |
| 204 |
if cost_so_far >= best_cost.load(Ordering::SeqCst) { |
| 205 |
return; |
| 206 |
} |
| 207 |
// Using `fetch_min` to avoid a race condition, in case it changed since `load`. |
| 208 |
best_cost.fetch_min(..., Ordering::SeqCst); |
| 209 |
} |
| 210 |
``` |
| 211 |
|
| 212 |
Now in this case, we really WANT to see results from other threads interjected |
| 213 |
into our execution! |