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 Apr 2, 2024
1 parent cf167b6 commit 88cbac8
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,16 @@ 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>`.
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 88cbac8

Please sign in to comment.