Created
September 9, 2011 10:42
-
-
Save Arachnid/1205924 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import heapq | |
class EventReactor(object): | |
"""Processes a set of EventStream and executes their events in order.""" | |
def __init__(self): | |
self.time = 0.0 # Current time | |
self.events = [] # Holds (time, event function, stream) tuples in a heapq | |
def add_stream(self, stream): | |
"""Adds an event stream to the reactor. | |
Args: | |
stream: An iterator that returns (interval, function) tuples. | |
""" | |
first_time, first_func = stream.next() | |
first_time += self.time | |
heapq.heappush(self.events, (first_time, first_func, stream)) | |
def run(self): | |
"""Executes events until all the streams are exhausted.""" | |
while self.events: | |
# Fetch the next event and execute it | |
new_time, func, stream = heapq.heappop(self.events) | |
self.time = new_time | |
func() | |
# Get the next event from this stream, if one exists, and add it back | |
try: | |
next_time, next_func = stream.next() | |
next_time += self.time | |
heapq.heappush(self.events, (next_time, next_func, stream)) | |
except StopIteration: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment