🤖 The AI Prompt That Audits a Function for Thread-Safety Gaps
Asking an AI assistant whether a function is thread-safe tends to get a confident yes-or-no answer with little to actually act on. A prompt that asks it to reason line by line about shared state, and to separate what’s definitely unsafe from what’s only unsafe under a specific ordering, turns a vague verdict into a concrete list of exactly where to add a lock, swap a collection type, or make something immutable.
🔎 The Problem
Is this function thread safe? [function body pasted alone, no field declarations] -> "It looks reasonably thread-safe, though as always, review carefully." No shared state identified, no line-level reasoning, nothing to fix.
✅ Fix: Ask for Line-Level Reasoning About Shared State, Not a Verdict
- The actual prompt: “Review this function assuming it can be called concurrently from multiple threads. For each field or variable it reads or writes that isn’t local to the function, tell me whether access to it is synchronized, what could go wrong if two threads hit this function at the same moment, and the minimal change that would close that specific gap. Don’t just say whether it’s thread-safe — show me the exact line where it isn’t.”
- Give it the actual field/member declarations above the function, not just the method body, since a shared-state audit is meaningless without seeing what’s actually shared.
- Ask it to separate “definitely unsafe,” “unsafe only under a specific ordering,” and “safe,” because lumping them together hides exactly the rare race that only shows up in production.
🚨 Why This Is Dangerous
- Accepting a blanket “looks thread-safe” answer without the line-level reasoning behind it can leave a race condition that only manifests under real concurrent load, long after a quick review already gave it a pass.
Thread-safety isn’t a property of a function in isolation — it’s a property of a function and everything else that might be touching the same state at the same time, and an audit that doesn’t name the shared state hasn’t actually audited anything.

