Python 多重处理不会让其余代码执行

问题描述 投票:0回答:1

好吧,在弄清楚线程之后,我正在学习如何在 Python 中进行多重处理,我编写的代码是一个简单的计时器,它每秒计数,直到用户在控制台中按 Enter 键结束程序。我使用线程编写了相同的程序并且它有效,但是当我尝试使用多处理执行相同的操作时,代码永远不会超过启动函数。有什么想法

import multiprocessing
import time

done = False


def timer():
    counter = 0
    while not done:
        time.sleep(1)
        counter += 1
        print(counter)


if __name__ == '__main__':
    p1 = multiprocessing.Process(target=timer())
    p1.start()
    # This code is never reached this works when using threads
    input("Press enter to quit")
    done = True
 
python
1个回答
0
投票

问题

您的代码的问题是您正在调用timer()函数,您应该将其作为目标传递给multiprocessing.Process。

你还写了

target=timer()
timer
会立即执行,而返回值,我想应该是None。

此外,你还有一个名为done的变量,它是一个共享标志,你需要管理主进程和子进程。这种情况需要在孩子看到更新的地方进行管理。

最重要的是,在创建流程时,请将其视为父子关系。

在您的情况下,最好的方法是使用

multiprocessing.Value
docs

multiprocessing.Event
文档

这里有一个代码片段来指导您

import multiprocessing
import time

def timer(done):
    counter = 0
    while not done.is_set():
        time.sleep(1)
        counter += 1
        print(counter)

if __name__ == '__main__':
    done = multiprocessing.Event()
    p1 = multiprocessing.Process(target=timer, args=(done,))
    p1.start()

    input("Press enter to quit\n")
    done.set()  # Signal the timer process to stop
    p1.join()   # Wait for the timer process to finish
© www.soinside.com 2019 - 2024. All rights reserved.