Guest User

Untitled

a guest
Apr 23rd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. import threading
  2. import time
  3. import random
  4.  
  5. class Ticker:
  6. def __init__ (self):
  7. self.currentTick = 0
  8. self.functionStatus = {}
  9.  
  10. def beginNextTick(self):
  11. for k, val in self.functionStatus.items():
  12. val.clear()
  13. val.wait()
  14. self.currentTick += 1
  15. return self.currentTick
  16.  
  17. def isDone (self, funcId):
  18. self.functionStatus[funcId].set()
  19.  
  20. def registerFunction (self, funcId):
  21. self.functionStatus[funcId] = threading.Event()
  22.  
  23. def waitForNewTick (self):
  24. for k, val in self.functionStatus.items():
  25. val.wait()
  26.  
  27. def getCurrentTick (self):
  28. return self.currentTick
  29.  
  30. def track (self, numTicks):
  31. while self.beginNextTick() < numTicks:
  32. pass
  33.  
  34.  
  35. def printDog(ticker, funcId):
  36. global dogRunning
  37.  
  38. while dogRunning:
  39. print(ticker.getCurrentTick(), funcId)
  40. ticker.isDone (funcId)
  41. ticker.waitForNewTick ()
  42.  
  43. def printCat(ticker, funcId):
  44. global catRunning
  45.  
  46. while catRunning:
  47. print(ticker.getCurrentTick(), funcId)
  48. ticker.isDone (funcId)
  49. ticker.waitForNewTick ()
  50.  
  51.  
  52. def startFunctionThreads(ticker):
  53. tArr = []
  54. for func in [printDog, printCat]:
  55. ticker.registerFunction(func.__name__)
  56. t = threading.Thread (target=func, args=(ticker, func.__name__))
  57. t.start()
  58. tArr.append (t)
  59.  
  60. return tArr
  61.  
  62.  
  63. if __name__ == "__main__":
  64.  
  65. dogRunning = True
  66. catRunning = True
  67.  
  68. ticker = Ticker()
  69. tArr = startFunctionThreads (ticker)
  70.  
  71. numTicks = 5000
  72. ticker.track(numTicks)
  73.  
  74. dogRunning = False
  75. catRunning = False
  76.  
  77. for t in tArr:
  78. t.join()
Add Comment
Please, Sign In to add comment