Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import heapq
- from types import coroutine
- class Task:
- thread_number = 0
- def __init__(self, func, *args, **kwargs):
- self.func = func
- self.complete = False
- self.args = args
- self.kwargs = kwargs
- def __lt__(self, value):
- return self.complete < value.complete
- def __eq__(self, value):
- return self.complete == value.complete
- @property
- def wait(self):
- yield from self.func(*self.args, **self.kwargs)
- self.complete = True
- class Loop:
- def __init__(self, *tasks):
- self.tasks = list(tasks)
- assert all(map(lambda f: isinstance(f, Task), tasks))
- self.processing = []
- def create_task(self, func):
- def wrapper(*args, **kwargs):
- self.tasks.append(
- Task(func, *args, **kwargs)
- )
- def run_until_complete(self):
- for task in self.tasks:
- _task = task.wait.send(None)
- heapq.heappush(self.processing, Task(_task))
- while self.processing:
- task = heapq.heappop(self.processing)
- if task.complete:
- continue
- try:
- func = next(task.wait)
- if not task.complete:
- heapq.heappush(self.processing, task)
- except StopIteration:
- continue
Advertisement
Add Comment
Please, Sign In to add comment