SKY-Q404 · Quality, structure and performance
Thread shared state mutation
A function started as a thread (threading.Thread(target=...)) changes a module-level list, dict or set, or a global, without taking a lock. Every thread running that function changes the same object.
- Languages
- Python
- Quality gate
- counted toward the gate limits (full and diff scans)
- Finding type
- review
Why it matters
view_counts[page] = view_counts.get(page, 0) + 1 is a read followed by a write. Two threads can read the same old value and both write it back plus one, so counts go missing. The numbers are a little wrong, never raise an error, and change from run to run.
What Skylos flags
"""Count page views from several worker threads.""" import threading view_counts = {} def count_views(events): for event in events: view_counts[event.page] = view_counts.get(event.page, 0) + 1 def run(batches): workers = [threading.Thread(target=count_views, args=(b,)) for b in batches] for worker in workers: worker.start() for worker in workers: worker.join() return view_countsWhat Skylos leaves alone
"""Count page views from several worker threads.""" import threading view_counts = {}counts_lock = threading.Lock() def count_views(events): for event in events: with counts_lock: view_counts[event.page] = view_counts.get(event.page, 0) + 1 def run(batches): workers = [threading.Thread(target=count_views, args=(b,)) for b in batches] for worker in workers: worker.start() for worker in workers: worker.join() return view_countsWhy Skylos leaves it alone
The thread target takes counts_lock around the update, so only one thread changes the dictionary at a time.
How Skylos decides
- Runs with
--qualityon Python files. Collects module-level names assigned a list, dict or set literal, a constant, or adict(),list(),set()ordefaultdict()call. - Finds functions defined at module level and passed by name as
target=to a call ofThread(orsomething.Thread) in the same file. - Skips the function when it uses any lock: a
withon a name containing "lock", "mutex" or "semaphore", or.acquire()/.release()on one. - Reports a write to an item or attribute of a shared name, a call of
append,extend,insert,pop,popitem,remove,clear,setdefault,sortorupdateon it, or an assignment to it afterglobal. One finding per name, MEDIUM, on the first change.
How to fix it
Avoid shared state: let each worker count its own batch and combine the results after the threads finish. A lock, as in the example above, also works.
"""Count page views from several worker threads.""" Removed: import threadingRemoved: Removed: view_counts = {}Added: from collections import CounterAdded: from concurrent.futures import ThreadPoolExecutor def count_views(events):Removed: for event in events:Removed: view_counts[event.page] = view_counts.get(event.page, 0) + 1Added: return Counter(event.page for event in events) def run(batches):Removed: workers = [threading.Thread(target=count_views, args=(b,)) for b in batches]Removed: for worker in workers:Removed: worker.start()Removed: for worker in workers:Removed: worker.join()Removed: return view_countsAdded: with ThreadPoolExecutor() as pool:Added: return sum(pool.map(count_views, batches), Counter())When it can be wrong
- Operations that are atomic in CPython, such as one
list.append()per thread, are reported, although they do not lose updates. - It misses targets given as methods (
target=self.run), lambdas or functions from another module, workers started through a thread pool, and functions that take a lock for a different object.
Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.
How to silence it
Put the marker on the reported line.
Python results.append(row) # skylos: ignore[SKY-Q404] list.append is atomic here[tool.skylos] ignore = ["SKY-Q404"]turns the rule off for the project.