我有两个要执行的功能。我需要它们同时运行直到发生例外情况,因此我使用了多处理,但是每当我执行我的代码时,它就从代码的开头无限地运行,那里有几行代码,然后是我的两个函数。我的代码如下所示:
'''
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
我的代码从头开始无限执行,或者问题出在其他地方,我的多处理是否有问题?
答案 0 :(得分:1)
您的代码中有一些要点。首先,如果您想执行多个功能,并不意味着每次都像当前一样创建多个进程。每个功能只需要一个进程或线程。 其次,我假设您希望您的函数永远同时运行,因此您需要将无限循环放入每个函数中。
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
答案 1 :(得分:1)
我认为您打算这样做:
'b'
这将在单独的进程中运行每个功能,并等待两个进程完成后再退出。另外,如果添加更多功能,则只需将它们添加到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
中,而不是复制和修改代码块。
答案 2 :(得分:0)
让主要进程进入睡眠状态,以使键盘中断:
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
此外,我认为在无限循环中创建新流程不是一个好习惯。