Guest User

Untitled

a guest
Mar 30th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. import threading
  2.  
  3.  
  4. class Task:
  5.     thread_number = 0
  6.  
  7.     def __init__(self, func, *args, **kwargs):
  8.         Task.thread_number += 1
  9.         self.func = func
  10.         self.args = args
  11.         self.kwargs = kwargs
  12.         self.thread_name = '#{} task {}'.format(
  13.             self.thread_number,
  14.             self.func.__name__
  15.         )
  16.  
  17.     def run_task(self):
  18.         thread = threading.Thread(
  19.             target=self.func,
  20.             name=self.thread_name,
  21.             args=self.args,
  22.             kwargs=self.kwargs
  23.         )
  24.  
  25.         self.thread = thread
  26.         thread.start()
  27.  
  28.     @property
  29.     def finished(self):
  30.         if not self.thread.isAlive():
  31.             return self.thread.join()
  32.         raise ValueError('incomplete')
  33.  
  34.  
  35. class Loop:
  36.     def __init__(self):
  37.         self.tasks = []
  38.         self.processing = []
  39.         self.completed = []
  40.  
  41.     def add_task(self, func):
  42.         def wrapper(*args, **kwargs):
  43.             task = Task(func, *args, **kwargs)
  44.             self.tasks.append(task)
  45.         return wrapper
  46.  
  47.     def run_until_complete(self):
  48.         for task in self.tasks:
  49.             task.run_task()
  50.             self.processing.append(task)
  51.         self.watcher()
  52.  
  53.     def watcher(self):
  54.         while len(self.processing):
  55.             to_delete = []
  56.             for n, task in enumerate(self.processing):
  57.                 try:
  58.                     completed = task.finished()
  59.                 except ValueError:
  60.                     continue
  61.  
  62.                 except TypeError:
  63.                     to_delete.append(n)
  64.  
  65.             for n in to_delete:
  66.                 completed = self.processing.pop(n)
  67.                 self.completed.append(completed)
  68.  
  69.     def coro(self, func):
  70.         self.tasks.append(func)
Advertisement
Add Comment
Please, Sign In to add comment