Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- class Task:
- thread_number = 0
- def __init__(self, func, *args, **kwargs):
- Task.thread_number += 1
- self.func = func
- self.args = args
- self.kwargs = kwargs
- self.thread_name = '#{} task {}'.format(
- self.thread_number,
- self.func.__name__
- )
- def run_task(self):
- thread = threading.Thread(
- target=self.func,
- name=self.thread_name,
- args=self.args,
- kwargs=self.kwargs
- )
- self.thread = thread
- thread.start()
- @property
- def finished(self):
- if not self.thread.isAlive():
- return self.thread.join()
- raise ValueError('incomplete')
- class Loop:
- def __init__(self):
- self.tasks = []
- self.processing = []
- self.completed = []
- def add_task(self, func):
- def wrapper(*args, **kwargs):
- task = Task(func, *args, **kwargs)
- self.tasks.append(task)
- return wrapper
- def run_until_complete(self):
- for task in self.tasks:
- task.run_task()
- self.processing.append(task)
- self.watcher()
- def watcher(self):
- while len(self.processing):
- to_delete = []
- for n, task in enumerate(self.processing):
- try:
- completed = task.finished()
- except ValueError:
- continue
- except TypeError:
- to_delete.append(n)
- for n in to_delete:
- completed = self.processing.pop(n)
- self.completed.append(completed)
- def coro(self, func):
- self.tasks.append(func)
Advertisement
Add Comment
Please, Sign In to add comment