Guest User

Untitled

a guest
Mar 30th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. import heapq
  2. from types import coroutine
  3.  
  4.  
  5. class Task:
  6.     thread_number = 0
  7.  
  8.     def __init__(self, func, *args, **kwargs):
  9.         self.func = func
  10.         self.complete = False
  11.         self.args = args
  12.         self.kwargs = kwargs
  13.  
  14.     def __lt__(self, value):
  15.         return self.complete < value.complete
  16.  
  17.     def __eq__(self, value):
  18.         return self.complete == value.complete
  19.  
  20.     @property
  21.     def wait(self):
  22.         yield from self.func(*self.args, **self.kwargs)
  23.         self.complete = True
  24.  
  25.  
  26. class Loop:
  27.     def __init__(self, *tasks):
  28.         self.tasks = list(tasks)
  29.         assert all(map(lambda f: isinstance(f, Task), tasks))
  30.         self.processing = []
  31.  
  32.     def create_task(self, func):
  33.         def wrapper(*args, **kwargs):
  34.             self.tasks.append(
  35.                 Task(func, *args, **kwargs)
  36.             )
  37.  
  38.     def run_until_complete(self):
  39.         for task in self.tasks:
  40.             _task = task.wait.send(None)
  41.             heapq.heappush(self.processing, Task(_task))
  42.  
  43.         while self.processing:
  44.             task = heapq.heappop(self.processing)
  45.  
  46.             if task.complete:
  47.                 continue
  48.  
  49.             try:
  50.  
  51.                 func = next(task.wait)
  52.                 if not task.complete:
  53.                     heapq.heappush(self.processing, task)
  54.  
  55.             except StopIteration:
  56.                 continue
Advertisement
Add Comment
Please, Sign In to add comment