我需要与“多处理”库并行运行多个类函数,但我无法找到针对我的特定问题的指南或答案。我的问题是只有第一个进程正在启动(或正在运行,我不知道这里的确切区别)。为了说明这个问题,我设置了以下示例:import multiprocessingimport timeclass 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()
1 回答
慕斯王
TA贡献1864条经验 获得超2个赞
正如您在 Python 文档中所读到的multiprocessing.Process,您需要为参数传递“调用对象” 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,则您不会像应该做的那样传递调用对象,而是调用该函数并传递返回值。
添加回答
举报
0/150
提交
取消