Skip to content

Clarify the difference between Lock and RLock when the acquiring thread returns #128167

@lzlarryli

Description

@lzlarryli

Documentation

Because RLock has an "owner", it is fully released when its acquiring thread exits, no matter how many times it is acquired. The ownerless Lock on the other hand, stays locked when its acquiring thread exits. This should be documented because it can lead to hard to debug errors.

Example code to see this difference:

def f(lock):
  print('f lock:', lock.acquire(False))
  print('f relock:', lock.acquire(False))
    

def g(lock):
  print('g lock:', lock.acquire(False))
  print('g relock:', lock.acquire(False))


print('Lock:')
lock = threading.Lock()
t1 = threading.Thread(target=f, args=(lock,))
t2 = threading.Thread(target=g, args=(lock,))
t1.start()
t1.join()
t2.start()
t2.join()
print()

print('RLock:')
lock = threading.RLock()
t1 = threading.Thread(target=f, args=(lock,))
t2 = threading.Thread(target=g, args=(lock,))
t1.start()
t1.join()
t2.start()
t2.join()

Output:

Lock:
f lock: True
f relock: False
g lock: False
g relock: False

RLock:
f lock: True
f relock: True
g lock: True
g relock: True

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions