liveBook · Manning

Race condition

As explained in Learn Go with Pocket-Sized Projects

A race condition is a correctness fault in which the result depends on the timing or interleaving of concurrent operations.

A Go HTTP server can handle a new request before an earlier handler finishes. Each request runs in a goroutine, so handlers that share state must account for concurrent access. Run tests with `go test -race` when checking for races. section 8.2.1

Protect a shared solution

Several maze-exploring goroutines may find the treasure and try to write `s.solution`. Lock a mutex before checking whether the field is nil and setting it; unlock when the operation is done. A separate `solutionFound` function uses the same mutex when reading the field. Protecting the write alone would leave the shared read unprotected. section 9.3.5

The solution field also acts as a signal for explorers to stop. This is a quick approach, not a complete shutdown design: whether the solver stops deadlocking can still depend on the maze. A cache that must support concurrent stores, reads, and deletes presents another shared-state problem to test. section 9.3.5 section 7.0

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Shows mutex-protected reads and writes in a maze solver, while leaving a reliable stopping design unresolved.
Examples
Uses concurrent maze explorers writing a solution, HTTP request handlers, and a cache required to be concurrency safe.
What you can do after
Diagnose/debug with `go test -race` and protect shared maze-solver state with a mutex.
How it connects
Connects goroutines, HTTP handlers, shared state, mutexes, caches, and deadlocks.

Also explained in

Compare how 20 books explain race condition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.