-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPyMultiThread.py
75 lines (67 loc) · 2.18 KB
/
PyMultiThread.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
import multiprocessing
import os
class processWrapper():
def __init__(self,proc,res,brk=lambda x: False):
self.process = proc
self.result = res
self.bp = brk
def run(self,pid,data,bpflag):
result = self.process(data)
self.result.put([data,result])
if self.bp(result):
print(pid,data,result)
bpflag.put(self.bp(result))
class bpHolder():
def __init__(self):
self.data = False
def __repr__(self):
return self.data.__repr__()
def __bool__(self):
return self.data
def put(self,newData):
self.data = self.data or newData
class resultGetter():
def __init__(self,dataholder):
self.data = dataholder
def put(self,newData):
self.data.put(newData[1])
def get(self):
return self.data
def rotatePool(targetProcess,dataPool,poolSize=os.cpu_count()):
processPool = []
breakCheck = bpHolder()
for i in range(poolSize):
tmpProcess = multiprocessing.Process(target=targetProcess.run,args=(i,dataPool.pop(),breakCheck))
processPool.append(tmpProcess)
processPool[i].start()
while len(dataPool) > 0 and (not breakCheck):
nextAvail = 0
while nextAvail < poolSize and processPool[nextAvail].is_alive():
nextAvail += 1
if nextAvail < poolSize:
processPool[nextAvail].join()
tmpProcess = multiprocessing.Process(target=targetProcess.run,args=(nextAvail,dataPool.pop(),breakCheck))
processPool[nextAvail]=tmpProcess
processPool[nextAvail].start()
for i in range(poolSize):
processPool[i].join()
# Example Process Starts Below:
def procWrap(data):
import example as test
result = test.primeTest(data)
print(data,result)
return result
def bWrap(result):
return result
def main():
import example as test
results=multiprocessing.SimpleQueue()
processWrap = processWrapper(procWrap,results,bWrap)
pendingPool = []
for i in range(100):
pendingPool.append(test.randNum(6))
rotatePool(processWrap,pendingPool)
while not results.empty():
print(results.get())
if __name__ == '__main__':
main()