Created
February 6, 2016 05:09
-
-
Save bbengfort/dc2aea53d4ca7fdef925 to your computer and use it in GitHub Desktop.
Shows how to implement a SimPy-like simulation using timeouts and generators.
This file contains 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
from collections import defaultdict | |
def blinker(env): | |
while True: | |
print 'Blink at {}!'.format(env.now) | |
yield 5 | |
class BlinkerEnvironment(object): | |
def __init__(self, blinkers=4): | |
self.now = 0 | |
self.blinkers = defaultdict(list) | |
for idx in xrange(blinkers): | |
# blinkers are scheduled by what they yield. | |
self.blinkers[idx].append(blinker(self)) | |
def run(self, until=100): | |
while self.now < until: | |
if self.now in self.blinkers: | |
for blinker in self.blinkers.pop(self.now): | |
timeout = blinker.next() + self.now | |
self.blinkers[timeout].append(blinker) | |
self.now = min(self.blinkers.keys()) | |
if __name__ == "__main__": | |
env = BlinkerEnvironment() | |
env.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment