← retour aux snippets

threading.local: stockage spécifique au thread

Isoler des variables par thread sans globals partagés.

python concurrency #threading#local#state

objectif

Isoler des variables par thread sans globals partagés.

code minimal

import threading, time
local = threading.local()
results = []
def worker(v):
    local.x = v
    time.sleep(0.001)
    results.append(local.x)

t1 = threading.Thread(target=worker, args=(1,))
t2 = threading.Thread(target=worker, args=(2,))
t1.start(); t2.start(); t1.join(); t2.join()
print(sorted(results) == [1,2])  # attendu: True

utilisation

import threading
tls = threading.local()
tls.user = "ada"
print(tls.user == "ada")

variante(s) utile(s)

import threading
tls = threading.local()
def f(): setattr(tls, "x", 1); return getattr(tls, "x", 0)
print(f() == 1)

notes

  • Chaque thread voit ses propres attributs sur l’objet local.
  • Pour asyncio, préférez contextvars.ContextVar.