繁体   English   中英

为什么我的代码从头开始无限运行,而不应该从头开始运行?

[英]Why my code is running from the beginning infinitely while it should not?

我有两个要执行的功能。 我需要它们同时运行直到发生例外情况,因此我使用了多处理,但是每当我执行我的代码时,它就从代码的开头无限地运行,那里有几行代码,然后是我的两个函数。 我的代码如下所示:

'''
few line of code
'''


def func_1():
    # Do Somthing


def func_2():
    # Do Somthing


while True:
    try:
        if __name__ == '__main__':
            sensor_process = Process(target=sensor)
            sensor_process.start()
            balance_process = Process(target=balance_fun)
            balance_process.start()
    except(KeyboardInterrupt, SystemExit):
        break

我的代码从头开始无限执行的多重处理是否有问题,或者问题出在其他地方?

您的代码中有几点。 首先,如果您想执行多个功能,并不意味着每次都像当前一样创建多个进程。 每个功能只需要一个进程或线程。 其次,我假设您希望您的函数永远同时运行,因此您需要将无限循环放入每个函数中。

from time import sleep
from multiprocessing import Process


def func_1():
    # Do Somthing
    while True:
        print("hello from func_1")
        sleep(1)

def func_2():
    # Do Somthing
    while True:
        print("hello from func_2")
        sleep(1)

if __name__ == '__main__':
    try:
        sensor_process = Process(target=func_1)
        sensor_process.start()
        balance_process = Process(target=func_2)
        balance_process.start()
        # if you set a control (flag) on both func_1 and func_2 then these two lines would wait until those flags released
        sensor_process.join()
        balance_process.join()
    except(KeyboardInterrupt, SystemExit):
        pass

我认为您打算这样做:

from multiprocessing import Process

def sensor():
    # Do Somthing
    pass

def balance_fun():
    # Do Somthing
    pass

if __name__ == '__main__':
    try:
        function_list = [sensor, balance_fun] 
        process_list = list()
        for function in function_list:
            proc = Process(target=function)
            proc.start()
            process_list.append(proc)
        for proc in process_list:
            proc.join()
    except(KeyboardInterrupt, SystemExit):
        pass

这将在单独的进程中运行每个功能,并等待两个进程完成后再退出。 另外,如果添加更多功能,则只需将它们添加到function_list而不是复制和修改代码块。

睡眠以获取键盘中断的主要过程:

while True:
    try:
        if __name__ == '__main__':
            sensor_process = Process(target=sensor)
            sensor_process.start()
            balance_process = Process(target=balance_fun)
            balance_process.start()

        time.sleep(1)

    except(KeyboardInterrupt, SystemExit):
        break

此外,我认为在无限循环中创建新流程不是一个好习惯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM