【发布时间】:2019-06-23 23:37:46
【问题描述】:
我正在尝试让一个多进程类对象在我的 python 程序的所有 cpu 内核中运行。代码有效,但它只在一个内核中运行。
我想知道子进程是否按顺序运行,但我找不到简单的方法来测试或避免它。
我的代码看起来像这样
#child processes
import multiprocessing as mp
import time
import random
class child(mp.Process):
def __init__(self,comm):
mp.Process.__init__(self)
self.comm = comm
def run(self):
self.score = self.doWork()
self.comm.put([self.score])
def doWork(self):
k = 0
for x in range(9999):
for y in range(9999):
k = k + 1
return random.randint(1,1000)
#main process
def runSubProcess():
list = []
queue = mp.Queue()
for p in range(4):
p = child(queue)
p.start()
p.join()
list.append(p)
stillRunning = True
while stillRunning:
stillRunning = False
for p in list:
if p.is_alive():
stillRunning = True
time.sleep(0.1)
while not queue.empty():
item = queue.get()
print (item)
if __name__ == "__main__":
runSubProcess()
我在使用 Windows 10 的 4 核环境中运行 python 3.8 64 位
版本字符串:
Win32 上的 Python 3.8.0a1(tags/v3.8.0a1:e75eeb00b5,2019 年 2 月 3 日,19:46:54)[MSC v.1916 32 位(英特尔)]
【问题讨论】:
标签: python python-multiprocessing