- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyMultiThread.py
More file actions
Latest commit
75 lines (67 loc) · 2.18 KB
/
Copy pathPyMultiThread.py
File metadata and controls
75 lines (67 loc) · 2.18 KB
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
importmultiprocessing
importos
classprocessWrapper():
def__init__(self,proc,res,brk=lambdax: False):
self.process=proc
self.result=res
self.bp=brk
defrun(self,pid,data,bpflag):
result=self.process(data)
self.result.put([data,result])
ifself.bp(result):
print(pid,data,result)
bpflag.put(self.bp(result))
classbpHolder():
def__init__(self):
self.data=False
def__repr__(self):
returnself.data.__repr__()
def__bool__(self):
returnself.data
defput(self,newData):
self.data=self.dataornewData
classresultGetter():
def__init__(self,dataholder):
self.data=dataholder
defput(self,newData):
self.data.put(newData[1])
defget(self):
returnself.data
defrotatePool(targetProcess,dataPool,poolSize=os.cpu_count()):
processPool= []
breakCheck=bpHolder()
foriinrange(poolSize):
tmpProcess=multiprocessing.Process(target=targetProcess.run,args=(i,dataPool.pop(),breakCheck))
processPool.append(tmpProcess)
processPool[i].start()
whilelen(dataPool) >0and (notbreakCheck):
nextAvail=0
whilenextAvail<poolSizeandprocessPool[nextAvail].is_alive():
nextAvail+=1
ifnextAvail<poolSize:
processPool[nextAvail].join()
tmpProcess=multiprocessing.Process(target=targetProcess.run,args=(nextAvail,dataPool.pop(),breakCheck))
processPool[nextAvail]=tmpProcess
processPool[nextAvail].start()
foriinrange(poolSize):
processPool[i].join()
# Example Process Starts Below:
defprocWrap(data):
importexampleastest
result=test.primeTest(data)
print(data,result)
returnresult
defbWrap(result):
returnresult
defmain():
importexampleastest
results=multiprocessing.SimpleQueue()
processWrap=processWrapper(procWrap,results,bWrap)
pendingPool= []
foriinrange(100):
pendingPool.append(test.randNum(6))
rotatePool(processWrap,pendingPool)
whilenotresults.empty():
print(results.get())
if__name__=='__main__':
main()