Arc<Mutex<Everything>>
Smell. Arc<Mutex<T>> (or Arc<RwLock<T>>) as the default answer
whenever two places touch the same data, including places that aren’t
concurrent. In advanced cases, nested:
Arc<Mutex<HashMap<String, Arc<Mutex<Entry>>>>>.
Why generation produces it. It compiles without restructuring: shared and mutable at once. Like cloning, it turns a design question (who owns this, who may mutate it, and when) into a local edit. It’s also very common in training data.
Principle. Try the alternatives before reaching for shared mutable state:
- Can one owner mutate, with others reading through short borrows? Use
plain
&mut. - Is this a pipeline? Move data through channels. Ownership transfers and nothing is shared.
- Is it read-mostly configuration? Use
Arc<T>without a lock. Immutable sharing needs no synchronization. - Only after these: shared mutable state, with the lock as a decision. Choose the granularity, keep hold times short, and document the acquisition order.
Prompt. “Restructure to avoid shared mutable state: single owner with
borrowed access where possible, channel-passed ownership for the
pipeline, Arc without a lock for immutable configuration. If a Mutex
remains, document which invariant it protects and why the state must be
both shared and mutable.”