-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallelWorker.py
128 lines (102 loc) · 2.6 KB
/
parallelWorker.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
#coding: utf-8
from multiprocessing import Process,Queue
from queue import Empty as QE
from threading import Thread
class QueueClearer(Thread):
"""
Class to empty the worker queue and store it in a list
(queues can lock the program when full)
Allows to get the return values on demand
"""
def __init__(self, q):
Thread.__init__(self)
self.l = []
self.go = True
self.q = q
def run(self):
while self.go:
try:
val = self.q.get(True,1)
self.l.append(val)
except QE:
pass
def getList(self):
l = len(self.l)
ret = []
for i in range(l):
ret.append(self.l.pop(0))
return ret
def stop(self):
self.go = False
class Worker:
"""
This class creates multiple processes to execute of fonction
asynchronously on large ammount of data. Once started,
it waits for data (given with feed(data)), executes the fonction
and stores the return value. It can then be recovered with .getRes()
/!\\ For now, order is not necessarily respected in the output !
"""
def __init__(self,**kwargs):
self.reslist = []
self.f = kwargs.get("target",lambda x:x)
self.N = kwargs.get("N",8)
self.qOut = Queue()
self.qIn = Queue()
self.p = []
def queuedF(qIn,qOut,f):
val = 0
while True:
try:
val = qIn.get(True,1)
if val is None:
break
qOut.put(f(val))
except QE:
pass
for i in range(self.N):
self.p.append(Process(target=queuedF,args=(self.qIn,self.qOut,self.f)))
self.qc = QueueClearer(self.qOut)
def start(self):
for i in range(self.N):
self.p[i].start()
self.qc.start()
def feed(self,data):
self.qIn.put(data)
def stop(self):
for i in range(self.N):
self.qIn.put(None)
for i in range(self.N):
self.p[i].join()
self.qc.stop()
self.qc.join()
print("Ended properly :)")
#print(self.qIn.qsize(),self.qOut.qsize())
def getRes(self):
return self.qc.getList()
# ============= Example ============
if __name__ == "__main__":
from time import sleep
import numpy as np
def doStuff(arr):
for i in range(500):
arr+=.002
arr-=.002
arr *= 1.5
arr /= 1.5
return arr+148
w = Worker(target=doStuff)
for i in range(500):
# It is possible to "pre-feed" before starting
w.feed(np.random.random((100,100)))
w.start()
for i in range(500):
w.feed(np.random.random((100,100)))
l = w.getRes()
print(len(l))
sleep(.5)
l.extend(w.getRes())
print(len(l))
w.stop()
l.extend(w.getRes())
print(len(l))
print(l[0])