Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import time
- import random
- class Ticker:
- def __init__ (self):
- self.currentTick = 0
- self.functionStatus = {}
- def beginNextTick(self):
- for k, val in self.functionStatus.items():
- val.clear()
- val.wait()
- self.currentTick += 1
- return self.currentTick
- def isDone (self, funcId):
- self.functionStatus[funcId].set()
- def registerFunction (self, funcId):
- self.functionStatus[funcId] = threading.Event()
- def waitForNewTick (self):
- for k, val in self.functionStatus.items():
- val.wait()
- def getCurrentTick (self):
- return self.currentTick
- def track (self, numTicks):
- while self.beginNextTick() < numTicks:
- pass
- def printDog(ticker, funcId):
- global dogRunning
- while dogRunning:
- print(ticker.getCurrentTick(), funcId)
- ticker.isDone (funcId)
- ticker.waitForNewTick ()
- def printCat(ticker, funcId):
- global catRunning
- while catRunning:
- print(ticker.getCurrentTick(), funcId)
- ticker.isDone (funcId)
- ticker.waitForNewTick ()
- def startFunctionThreads(ticker):
- tArr = []
- for func in [printDog, printCat]:
- ticker.registerFunction(func.__name__)
- t = threading.Thread (target=func, args=(ticker, func.__name__))
- t.start()
- tArr.append (t)
- return tArr
- if __name__ == "__main__":
- dogRunning = True
- catRunning = True
- ticker = Ticker()
- tArr = startFunctionThreads (ticker)
- numTicks = 5000
- ticker.track(numTicks)
- dogRunning = False
- catRunning = False
- for t in tArr:
- t.join()
Add Comment
Please, Sign In to add comment