forked from mcvoramet/AltoAcademy-Advance-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
8 RLock.py
49 lines (33 loc) · 879 Bytes
/
8 RLock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import threading
# Using Lock
lock = threading.Lock()
def factorial_with_lock(n):
if n == 1:
return 1
# Acquiring the lock
lock.acquire()
# Recursively calling the function
result = n * factorial_with_lock(n - 1)
# Releasing the lock
lock.release()
return result
# Using RLock
rlock = threading.RLock()
def factorial_with_rlock(n):
if n == 1:
return 1
# Acquiring the lock
rlock.acquire()
# Recursively calling the function
result = n * factorial_with_rlock(n - 1)
# Releasing the lock
rlock.release()
return result
# Testing
try:
print("Using Lock:")
print(factorial_with_lock(5)) # This will cause a deadlock
except RuntimeError as e:
print("Error:", e)
print("\nUsing RLock:")
print(factorial_with_rlock(5)) # This will work properly