Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shows how to implement a SimPy-like simulation using timeouts and generators.
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