Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

MPWorker.py 4.2 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
  1. import multiprocessing
  2. import threading
  3. import time
  4. import traceback
  5. import weakref
  6. from typing import List
  7. class MPWorker:
  8. def __init__(self, sub_args : List = None,
  9. process_count : int = None ):
  10. """
  11. base class for multi process worker
  12. provides messaging interface between host and subprocesses
  13. sub_args a list of args will be passed to _on_sub_initialize
  14. process_count number of subprocesses. Default : number of cpu count
  15. starts immediatelly after construction.
  16. """
  17. if process_count is None:
  18. process_count = multiprocessing.cpu_count()
  19. pipes = []
  20. ps = []
  21. for i in range(process_count):
  22. host_pipe, sub_pipe = multiprocessing.Pipe()
  23. p = multiprocessing.Process(target=self._sub_process, args=(i, process_count, sub_pipe, sub_args), daemon=True)
  24. p.start()
  25. pipes += [host_pipe]
  26. ps += [p]
  27. self._process_id = -1
  28. self._process_count = process_count
  29. self._process_working_count = process_count
  30. self._pipes = pipes
  31. self._ps = ps
  32. threading.Thread(target=_host_thread_proc, args=(weakref.ref(self),), daemon=True).start()
  33. # overridable
  34. def _on_host_sub_message(self, process_id, name, *args, **kwargs):
  35. """a message from subprocess"""
  36. # overridable
  37. def _on_sub_host_message(self, name, *args, **kwargs):
  38. """a message from host"""
  39. # overridable
  40. def _on_sub_initialize(self, *args):
  41. """on subprocess initialization"""
  42. # overridable
  43. def _on_sub_finalize(self):
  44. """on graceful subprocess finalization"""
  45. # overridable
  46. def _on_sub_tick(self, process_id):
  47. """"""
  48. def get_process_count(self) -> int: return self._process_count
  49. def get_process_id(self) -> int: return self._process_id
  50. def kill(self):
  51. """
  52. kill subprocess
  53. """
  54. for p in self._ps:
  55. p.kill()
  56. self._ps = []
  57. def stop(self):
  58. """
  59. graceful stop subprocess, will wait all subprocess finalization
  60. """
  61. self._send_msg('__stop')
  62. for p in self._ps:
  63. p.join()
  64. self._ps = []
  65. def _host_process_messages(self, timeout : float = 0) -> bool:
  66. """
  67. process messages on host side
  68. """
  69. for process_id, pipe in enumerate(self._pipes):
  70. try:
  71. if pipe.poll(timeout):
  72. name, args, kwargs = pipe.recv()
  73. if name == '__stopped':
  74. self._process_working_count -= 1
  75. else:
  76. self._on_host_sub_message(process_id, name, *args, **kwargs)
  77. except:
  78. ...
  79. def _send_msg(self, name, *args, process_id=-1, **kwargs):
  80. """
  81. send message to other side
  82. process_id -1 mean send to all sub processes
  83. on subprocess side - ignore this param
  84. """
  85. try:
  86. for i, pipe in enumerate(self._pipes):
  87. if process_id == -1 or i == process_id:
  88. pipe.send( (name, args, kwargs) )
  89. except:
  90. ...
  91. def _sub_process(self, process_id, process_count, pipe, sub_args):
  92. self._process_id = process_id
  93. self._process_count = process_count
  94. self._pipes = [pipe]
  95. self._on_sub_initialize(*sub_args)
  96. working = True
  97. while working:
  98. self._on_sub_tick(process_id)
  99. if pipe.poll(0.005):
  100. while True:
  101. name, args, kwargs = pipe.recv()
  102. if name == '__stop':
  103. working = False
  104. else:
  105. try:
  106. self._on_sub_host_message(name, *args, **kwargs)
  107. except:
  108. print(f'Error during handling host message {name} : {traceback.format_exc()}')
  109. if not pipe.poll():
  110. break
  111. self._on_sub_finalize()
  112. def _host_thread_proc(wref):
  113. while True:
  114. ref = wref()
  115. if ref is None:
  116. break
  117. ref._host_process_messages(0)
  118. del ref
  119. time.sleep(0.005)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...