← retour aux snippets

threading.RLock: verrou réentrant

Permettre la réentrée par le même thread pour éviter les deadlocks.

python concurrency #threading#lock

objectif

Permettre la réentrée par le même thread pour éviter les deadlocks.

code minimal

import threading
lock = threading.RLock()
ok = False
with lock:
    with lock:
        ok = True
print(ok)  # attendu: True

utilisation

import threading
r = threading.RLock()
def f():
    with r:
        with r:
            return True
print(f())

variante(s) utile(s)

import threading
l = threading.Lock()
l.acquire()
print((l.locked(), True)[0])
l.release()

notes

  • RLock supporte des acquisitions imbriquées par le même thread.
  • Pour des locks simples sans réentrée, utilisez Lock.