Advertisement
Guest User

Untitled

a guest
Apr 20th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. import threading
  2. import time
  3.  
  4. class Data_frame():
  5.     lock_var_1 = threading.Lock() # Global lock on the data_frame obj
  6.     var_1 = 0
  7.     var_2 = 0
  8.  
  9.    
  10. class Worker_1(threading.Thread):
  11.     def __init__(self, data_frame, time):
  12.         threading.Thread.__init__(self)
  13.         self.daemon = True # Cause CMD window and i like CTRL + C
  14.         self.data = data_frame
  15.         self.time = time
  16.    
  17.     def run(self):
  18.         while True :
  19.             print("{} : Waiting for DATA lock".format(self.name))
  20.             self.data.lock_var_1.acquire()
  21.             try:
  22.                 print("{} : Acquired DATA lock".format(self.name))
  23.                 print("{} : Doing some work".format(self.name))
  24.                 dummy = self.data.var_1
  25.                 time.sleep(self.time) # That's not really but it holds the lock
  26.                 self.data.var_1 = dummy + 1
  27.                 print("{} : Finished some work = > {}".format(self.name, self.data.var_1))
  28.             finally:
  29.                 self.data.lock_var_1.release()
  30.                 print("{} : Release DATA lock".format(self.name))
  31.            
  32.            
  33.            
  34. class Worker_2(threading.Thread):
  35.     def __init__(self, data_frame, time):
  36.         threading.Thread.__init__(self)
  37.         self.daemon = True # Cause CMD window and i like CTRL + C
  38.         self.data = data_frame
  39.         self.time = time
  40.    
  41.     def run(self):
  42.         while True :
  43.             print("{} : Doing some work".format(self.name))
  44.             dummy = self.data.var_2
  45.             time.sleep(self.time) # That's not really but it holds the lock
  46.             self.data.var_2 = dummy + 1
  47.             print("{} : Finished some work      = > {}".format(self.name, self.data.var_2))
  48.            
  49.  
  50.        
  51. class Main_frame():
  52.     def __init__(self):
  53.         self.data = Data_frame()
  54.        
  55.         self.worker_type_1_n1 = Worker_1(self.data, 2)
  56.         self.worker_type_1_n2 = Worker_1(self.data, 4)
  57.         self.worker_type_2_n1 = Worker_2(self.data, 1)
  58.        
  59.     def start(self):
  60.         self.worker_type_1_n1.start()
  61.         self.worker_type_1_n2.start()
  62.         self.worker_type_2_n1.start()
  63.        
  64. def main():
  65.     example = Main_frame()
  66.     example.start()
  67.     time.sleep(30)
  68.  
  69. if __name__ == "__main__":
  70.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement