Skip to main content

SKY-Q404 · Quality, structure and performance

Thread shared state mutation

Medium

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
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

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

analytics/views.py · PythonReported on line 10
"""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_counts

What Skylos leaves alone

analytics/views.py · Python
"""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_counts

Why 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

  1. Runs with --quality on Python files. Collects module-level names assigned a list, dict or set literal, a constant, or a dict(), list(), set() or defaultdict() call.
  2. Finds functions defined at module level and passed by name as target= to a call of Thread (or something.Thread) in the same file.
  3. Skips the function when it uses any lock: a with on a name containing "lock", "mutex" or "semaphore", or .acquire()/.release() on one.
  4. Reports a write to an item or attribute of a shared name, a call of append, extend, insert, pop, popitem, remove, clear, setdefault, sort or update on it, or an assignment to it after global. 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.

analytics/views.py · Python · the fix, against the flagged file
"""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.

From the Skylos rule handbook, Skylos 5.8.0 (commit 5b880b0). All rules.