Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. build an engine
  2. +-- weld metal
  3. +-- screw bolts
  4.  
  5. build a car
  6. +-- build an engine
  7. | +-- weld metal
  8. | +-- screw bolts
  9. +-- build a frame
  10. | +-- weld metal
  11. | +-- screw bolts
  12. | +-- paint
  13. +-- combine engine and frame
  14.  
  15. class Task:
  16. def do(self):
  17. raise NotImplementedError('abstract method')
  18.  
  19. class Job(Task):
  20. def __init__(self):
  21. self.tasks = []
  22.  
  23. def do(self):
  24. for task in self.tasks:
  25. task.do()
  26.  
  27. class Task:
  28. def do(self):
  29. raise NotImplementedError('abstract method')
  30.  
  31. def run(self):
  32. if self.block:
  33. self.do()
  34. else:
  35. threading.Thread(target=self.do).start()
  36.  
  37. class Task:
  38. def __init__(self):
  39. self._done = threading.Event()
  40. self.dependencies = []
  41.  
  42. def wait_for_completion(self):
  43. self._done.wait()
  44.  
  45. def do(self):
  46. raise NotImplementedError('abstract method')
  47.  
  48. def do_async(self):
  49. for depends in self.dependencies:
  50. depends.wait_for_completion()
  51.  
  52. self.do()
  53. self._done.set()
  54.  
  55. def run(self):
  56. threading.Thread(target=self.do_async).start()
  57.  
  58.  
  59. class Job(Task):
  60. def __init__(self):
  61. super(Job, self).__init__()
  62. self.tasks = []
  63.  
  64. def do(self):
  65. started_tasks = []
  66. for task in self.tasks:
  67. if task.block:
  68. self._wait_for_tasks(started_tasks)
  69. started_tasks = []
  70. else:
  71. started_tasks.append(task)
  72. task.run()
  73. if task.block:
  74. task.wait_for_completion()
  75. self._wait_for_tasks(self.tasks)
  76.  
  77. def _wait_for_tasks(self, task_list):
  78. for task in task_list:
  79. task.wait_for_completion()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement