-
Notifications
You must be signed in to change notification settings - Fork 2
/
multi_process.py
337 lines (250 loc) · 8.8 KB
/
multi_process.py
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# -*- coding: utf-8 -*-
#
# Author: Daniel Garcia (cr0hn) - @ggdaniel
# Github: https://github.com/cr0hn
#
import asyncio
from multiprocessing import Process
from threading import Thread, Event, BoundedSemaphore, currentThread
class _ConcurrentManager(object):
def __init__(self, n_process=2, n_threads=5, n_tasks=10, daemon=False):
"""
:param n_process:
:type n_process:
:param n_threads:
:type n_threads:
:param n_tasks:
:type n_tasks:
:param daemon:
:type daemon:
"""
self.daemon = daemon
self.n_taks = n_tasks
self.n_threads = n_threads
self.n_process = n_process
self.sem_threads = BoundedSemaphore(self.n_threads)
self.sem_tasks = asyncio.BoundedSemaphore(self.n_taks)
self.running_process = []
# --------------------------------------------------------------------------
# Public methods
# --------------------------------------------------------------------------
def run(self):
self._launch_processes()
def wait_until_complete(self):
try:
for x in self.running_process:
x.join()
except KeyboardInterrupt:
print("\n[*] CTRL+C Caught. ...")
for x in self.running_process:
x.terminate()
# --------------------------------------------------------------------------
# Private launchers
# --------------------------------------------------------------------------
# Asyncio task launcher
def _launch_tasks(self, name, state, sem):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self._tasks_worker_manager(loop, name, state))
except KeyboardInterrupt:
# Canceling tasks
tasks = asyncio.Task.all_tasks()
map(asyncio.Task.cancel, tasks)
loop.run_forever()
tasks.exception()
finally:
loop.close()
sem.release()
# Thread launcher the pool
def _launch_threads(self, proc_number):
state = Event()
th = []
try:
while True:
if state.isSet():
break
n = "proc-%s" % proc_number
t = Thread(target=self._launch_tasks, args=(n, state, self.sem_threads,))
th.append(t)
# t.daemon = True
t.start()
self.sem_threads.acquire()
for t in th:
t.join()
except KeyboardInterrupt:
# print("\n[*] CTRL+C Caught. Exiting threads form process '%s'..." % proc_number)
pass
finally:
state.set()
# Process launcher the pool
def _launch_processes(self):
try:
for i in range(self.n_process):
p = Process(target=self._launch_threads, args=(i,))
if self.daemon is True:
p.daemon = True
self.running_process.append(p)
p.start()
if self.daemon is False:
for x in self.running_process:
x.join()
except KeyboardInterrupt:
for x in self.running_process:
x.terminate()
# --------------------------------------------------------------------------
# Scalability methods
# --------------------------------------------------------------------------
@property
def threads_num(self):
"""
:return: Return the current active threads
:rtype: int
"""
return self.sem_threads._value
def threads_inc(self, n):
"""
Increases the thread pool in 'n'.
:param n: number which increment the thread pool
:type n: int
"""
self.sem_threads._value += n
if self.sem_threads._value < self.sem_threads._initial_value:
self.sem_threads.release()
def threads_dec(self, n):
"""
Decreases the threads number in 'n'
:param n: number which decrement the thread pool
:type n: int
"""
if n > 0:
if self.sem_threads._value - n > 1:
self.sem_threads._value -= n
@property
def tasks_num(self):
"""
:return: Return the current active asyncio tasks
:rtype: int
"""
return self.sem_tasks._value
def tasks_inc(self, n):
"""
Increases the asyncio tasks pool in 'n'.
:param n: number which increment the asyncio Task pool
:type n: int
"""
self.sem_tasks._value += n
if self.sem_tasks._value < self.sem_tasks._bound_value:
self.sem_tasks.release()
def tasks_dec(self, n):
"""
Decreases the asyncio Tasks number in 'n'
:param n: number which decrement the tasks pool
:type n: int
"""
if n > 0:
if self.sem_tasks._value - n > 1:
self.sem_tasks._value -= n
class SimpleConcurrencyManager(_ConcurrentManager):
def __init__(self, co_to_run, n_process=2, n_threads=5, n_tasks=10, daemon=False):
self.co_to_run = co_to_run
super(SimpleConcurrencyManager, self).__init__(n_process, n_threads, n_tasks, daemon)
# Task pool
@asyncio.coroutine
def _tasks_worker_manager(self, loop, name, state):
while True:
if state.isSet():
break
yield from self.sem_tasks.acquire()
loop.create_task(self.co_to_run(name, state))
class AdvancedConcurrencyManager(_ConcurrentManager):
def __init__(self, coro_map, n_process=2, n_threads=5, n_tasks=10, daemon=False):
"""
coro_map is a dict with pointer to coroutines and the number os task assigned to each one.
Example:
>>> fn_map = (
(coro_fn_1, 3),
(coro_fn_2, 4),
(coro_fn_3, 3),
)
>>> c = AdvancedConcurrencyManager(coro_map=fn_map)
>>> c.run()
"""
self.co_to_run = coro_map
self.round_robin_round = []
self.turn = 0
# Build a Semaphore per each coro function
for coro_fn, instances in coro_map:
for x in range(instances):
# Add priority fn
self.round_robin_round.append(coro_fn)
if len(self.round_robin_round) != n_tasks:
raise ValueError("The summation of all of tasks slots do not match with the tasks number")
super(AdvancedConcurrencyManager, self).__init__(n_process, n_threads, n_tasks, daemon)
# Task pool
@asyncio.coroutine
def _tasks_worker_manager(self, loop, name, state):
while True:
if state.isSet():
break
# Get the round turn
coro_next = self.round_robin_round[self.turn]
# Set next turn
self.turn += 1
if self.turn >= len(self.round_robin_round):
self.turn = 0
yield from self.sem_tasks.acquire()
loop.create_task(coro_next(name, state))
@asyncio.coroutine
def task1(t, e):
"""
A task
:param e: Event obj
:type e: Event
"""
import random
for x in range(200):
print(t, " - ", currentThread().name, " - task-1-%s" % random.randint(1, 100000))
yield from asyncio.sleep(1)
@asyncio.coroutine
def task2(t, e):
"""
A task
:param e: Event obj
:type e: Event
"""
import random
for x in range(200):
print(t, " - ", currentThread().name, " - task-2-%s" % random.randint(1, 100000))
yield from asyncio.sleep(1)
if __name__ == '__main__':
#
# This code build this process-> threads-> asyncio tasks distribution:
#
# main -> Process 1 -> Thread 1.1 -> Task 1.1.1
# -> Task 1.1.2
# -> Task 1.1.3
#
# -> Thread 1.2
# -> Task 1.2.1
# -> Task 1.2.2
# -> Task 1.2.3
#
# Process 2 -> Thread 2.1 -> Task 2.1.1
# -> Task 2.1.2
# -> Task 2.1.3
#
# -> Thread 2.2
# -> Task 2.2.1
# -> Task 2.2.2
# -> Task 2.2.3
import time
# c = ConcurrentManager(n_process=1, n_taks=2, n_threads=2, daemon=True)
# c = SimpleConcurrencyManager(task1, n_process=1, n_threads=10, n_tasks=20)
# c.run()
tasks = (
(task1, 2),
(task2, 8)
)
c = AdvancedConcurrencyManager(tasks, n_process=2, n_threads=10, n_tasks=10)
c.run()