Python v3.10
- the RLock (reentral) lock in Python is a thread aware lock that can be unlocked by only one thread at the time (has other benefits, but that's off topic in this test)
- the expected behavior in the below example: we have 3 threads, only one of them should be able to acquire (unlock) the RLock, but more than one acquires the same RLock when there's no work in the thread
Unexpected behavior:
import threading
lock = threading.RLock()
def th(name):
print( f"{name} tread started")
lock.acquire()
print( f"{name} tread end")
th1 = threading.Thread(target=th, args=[1])
th2 = threading.Thread(target=th, args=[2])
th3 = threading.Thread(target=th, args=[3])
th1.start()
th2.start()
th3.start()
Output ->
1 tread started
1 tread end
2 tread started
2 tread end
3 tread started
3 tread end
We can clearly see that all 3 threads unlocks the RLock (sometimes 2 sometimes 3)
Expected behavior:
import threading
import time
lock = threading.RLock()
def th(name):
print( f"{name} tread started")
lock.acquire()
time.sleep(0.1) # simulating some work
print( f"{name} tread end")
th1 = threading.Thread(target=th, args=[1])
th2 = threading.Thread(target=th, args=[2])
th3 = threading.Thread(target=th, args=[3])
th1.start()
th2.start()
th3.start()
Output ->
1 tread started
2 tread started
3 tread started
1 tread end
When there's some work the RLock does its thing (acquired by thread1 and block thread2 and thread3 untill thread1 releases the RLock) I tired this with loops too, but it seems when there's no or very little work in threads the RLock acquired by multiple threads
- Is this a bug? or am I doing wrong something?