Skip to content

Instantly share code, notes, and snippets.

@bbengfort
Created February 6, 2016 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbengfort/dc2aea53d4ca7fdef925 to your computer and use it in GitHub Desktop.
Save bbengfort/dc2aea53d4ca7fdef925 to your computer and use it in GitHub Desktop.
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