【问题标题】:Why is my python multiprocess program running only in one core?为什么我的 python 多进程程序只在一个内核中运行?
【发布时间】: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


    【解决方案1】:

    因为你启动后立即join()它。这使得主程序等待子程序完成。

    首先启动它们,然后将它们全部加入另一个循环,如下所示:

    def runSubProcess():
         list = []
         queue = mp.Queue()
         for p in range(4):
             p = child(queue)
             p.start()
             list.append(p)
         for p in list:
             p.join()
         while not queue.empty():
             item = queue.get()
             print (item)
    

    请注意,不需要休眠,因为join() 会在需要时自行“休眠” - 更好的是:不使用任何 CPU。

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多