Created
July 22, 2022 17:03
-
-
Save ronaldpetty/1a558276e2ee38f51991b35fed2bdbf9 to your computer and use it in GitHub Desktop.
RLock Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
class X: | |
def __init__(self): | |
self.a = 1 | |
self.b = 2 | |
self.lock = threading.RLock() | |
def changeA(self): | |
print(f"{threading.current_thread().name} waiting in changeA") | |
with self.lock: | |
print(f"{threading.current_thread().name} starting processing in changeA") | |
time.sleep(5) | |
self.a = self.a + 1 | |
def changeB(self): | |
print(f"{threading.current_thread().name} waiting in changeB") | |
with self.lock: | |
print(f"{threading.current_thread().name} starting processing in changeB") | |
self.b = self.b + self.a # this is an issue, as a can change while using it, should add a lock to access a | |
def changeAandB(self): | |
print(f"{threading.current_thread().name} waiting in changeAandB") | |
with self.lock: | |
print(f"{threading.current_thread().name} starting processing in changeAandB") | |
self.changeA() # using rlock allows us the self.lock to be called again | |
self.changeB() | |
if __name__ == "__main__": | |
x = X() | |
t1 = threading.Thread(target=x.changeA) | |
t1.start() | |
x.changeA() # like a normal lock, we can't do anything until we get it | |
t1.join() | |
print("---") | |
t2 = threading.Thread(target=x.changeAandB) | |
t2.start() | |
x.changeB() # this can't happen until t2 is finished | |
t2.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment