python 多处理没有给出输出

python multiprocessing is not giving output

我刚刚了解到 python 多处理,并尝试通过以下方式应用它:

这里 class A 将继承 运行 class B multiprocessing.Process

import multiprocessing as mp

class A:
    def __init__(self, num_workers=mp.cpu_count()):
        self.num_workers = num_workers
        self.x = 5
    
    def process(self):
        workers = []
        for i in range(self.num_workers):
            workers.append(B(self.x))
        for worker in workers:
            worker.start()
        for worker in workers:
            worker.join()

class B(mp.Process):
    def __init__(self, val):
        mp.Process.__init__(self)
        self.val = val
        
    def square(self):
        print(self.val * self.val)
    
    def run(self):
        self.square()

最终以这种方式将 classes 调用到 运行 平方函数:

a = A()
a.process()

但是我没有得到任何输出。

请注意,这是另一个代码的虚拟微版本,由于某些问题,我正在尝试将其多线程转换为多处理。

像这样称呼你的类

if __name__ == '__main__':
    a = A()
    a.process()

阅读 Safe importing of main module 了解有关原因的更多信息