我需要与“ multiprocessing”库并行运行多个类函数,但无法找到针对特定问题的指南或答案。 我的问题是只有第一个进程正在启动(或者正在运行,我不知道确切的区别)。
为说明问题,我设置了以下示例:
import multiprocessing
import time
class parallel_printer(multiprocessing.Process):
def __init__(self, freq_0, freq_1, freq_2):
self.freq_0 = freq_0
self.freq_1 = freq_1
self.freq_2 = freq_2
def print_0(self):
while True:
now = time.localtime()
if now.tm_sec % self.freq_0 == 0:
print('printer 0')
time.sleep(1.0)
def print_1(self):
while True:
now = time.localtime()
if now.tm_sec % self.freq_1 == 0:
print('printer 1')
time.sleep(1.0)
def print_2(self):
while True:
now = time.localtime()
if now.tm_sec % self.freq_2 == 0:
print('printer 2')
time.sleep(1.0)
def start_printer(self):
p_0 = multiprocessing.Process(target = self.print_0())
p_1 = multiprocessing.Process(target = self.print_1())
p_2 = multiprocessing.Process(target = self.print_2())
p_0.start()
p_1.start()
p_2.start()
class Tester(object):
def __init__(self):
self.freq_0 = 3
self.freq_1 = 7
self.freq_2 = 11
self.parallel_printer = parallel_printer(self.freq_0, self.freq_1, self.freq_2)
def start_Tester(self):
self.parallel_printer.start_printer()
if __name__ == '__main__':
tester = Tester()
tester.start_Tester()
答案 0 :(得分:5)
正如您在multiprocessing.Process
的Python文档中可以看到的那样,您需要为target
参数传递“调用对象”。
您的代码应如下所示:
p_0 = multiprocessing.Process(target=self.print_0)
p_1 = multiprocessing.Process(target=self.print_1)
p_2 = multiprocessing.Process(target=self.print_2)
如果您写的是self.print_0()
而不是self.print_0
,则说明您没有传递调用对象,而是调用函数并传递了返回值。