Skip to content

Commit

Permalink
Change example with race conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianKnodt committed Mar 31, 2024
1 parent cf167b6 commit 71c8b88
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions FAQ.md
Expand Up @@ -210,16 +210,19 @@ way, when you are searching down some path that's already longer than
this shortest route, you can just stop and avoid wasted effort. In
sequential land, you might model this "best result" as a shared value
like `Rc<Cell<usize>>` (here the `usize` represents the length of best
path found so far); in parallel land, you'd use a `Arc<AtomicUsize>`.
path found so far); in parallel land, you'd use a `&AtomicUsize`.
Note that `Arc` is no longer necessary because atomic types provide interior mutability.
Now we can make our search function look like:

```rust
fn search(path: &Path, cost_so_far: usize, best_cost: &Arc<AtomicUsize>) {
fn search(path: &Path, cost_so_far: usize, best_cost: &AtomicUsize) {
if cost_so_far >= best_cost.load(Ordering::SeqCst) {
return;
}
...
best_cost.store(...);
// Note: doing `best_cost.store(...)` will introduce race conditions.
// Using `fetch_*` such as `fetch_min` will help prevent race conditions.
best_cost.fetch_min(cost_so_far, Ordering::SeqCst);
}
```

Expand Down

0 comments on commit 71c8b88

Please sign in to comment.