I have two functions that are going to do something. I need them to run simultaneously until the except case happen, so I have used multiprocessing but whenever I execute my code, it runs from beginning of the code infinitely which there is a few line of code and then my two functions. My code looks something like this:
'''
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
Is there anything wrong with my multiprocessing that my code executes from the beginning infinitely or the problem is somewhere else?
There are some points on your code. First, if you want to execute multiple functions it doesn't mean to create multiple processes each time as you currently doing. You only need one process or thread per function. Second I assume you want your functions run simultaneously forever so you need to put the infinite loop inside each function.
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
I think you meant to do something like this:
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
This will run each function in a separate process and wait for both processes to finish before exiting. Also, if you add more functions, you just need to add them to function_list
instead of copying and modifying a block of code.
put a sleep for the main process to get your keyboard interrupt:
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
besides, I think creating new processes in an infinite loop is not a good practice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.