Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import time
- class Data_frame():
- lock_var_1 = threading.Lock() # Global lock on the data_frame obj
- var_1 = 0
- var_2 = 0
- class Worker_1(threading.Thread):
- def __init__(self, data_frame, time):
- threading.Thread.__init__(self)
- self.daemon = True # Cause CMD window and i like CTRL + C
- self.data = data_frame
- self.time = time
- def run(self):
- while True :
- print("{} : Waiting for DATA lock".format(self.name))
- self.data.lock_var_1.acquire()
- try:
- print("{} : Acquired DATA lock".format(self.name))
- print("{} : Doing some work".format(self.name))
- dummy = self.data.var_1
- time.sleep(self.time) # That's not really but it holds the lock
- self.data.var_1 = dummy + 1
- print("{} : Finished some work = > {}".format(self.name, self.data.var_1))
- finally:
- self.data.lock_var_1.release()
- print("{} : Release DATA lock".format(self.name))
- class Worker_2(threading.Thread):
- def __init__(self, data_frame, time):
- threading.Thread.__init__(self)
- self.daemon = True # Cause CMD window and i like CTRL + C
- self.data = data_frame
- self.time = time
- def run(self):
- while True :
- print("{} : Doing some work".format(self.name))
- dummy = self.data.var_2
- time.sleep(self.time) # That's not really but it holds the lock
- self.data.var_2 = dummy + 1
- print("{} : Finished some work = > {}".format(self.name, self.data.var_2))
- class Main_frame():
- def __init__(self):
- self.data = Data_frame()
- self.worker_type_1_n1 = Worker_1(self.data, 2)
- self.worker_type_1_n2 = Worker_1(self.data, 4)
- self.worker_type_2_n1 = Worker_2(self.data, 1)
- def start(self):
- self.worker_type_1_n1.start()
- self.worker_type_1_n2.start()
- self.worker_type_2_n1.start()
- def main():
- example = Main_frame()
- example.start()
- time.sleep(30)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement