我的任务是更新当前作为单个进程运行的现有 python 程序,以同时运行子进程。我是 python 并发技术的新手,并编写了一个简单的脚本来了解如何使用 multiprocessing
库来做到这一点:
import datetime
import logging
import multiprocessing as mp
import time
from multiprocessing import Process
def child_operation():
"""Run a child process."""
name = 'child'
period = 1
logging.info(f"{datetime.datetime.now()}: started operation {name}")
for i in range(10):
logging.info(f"operation {name}, {i=}: sleeping for period {period} sec")
time.sleep(period)
logging.info(f"{datetime.datetime.now()}: ended operation {name}")
def main():
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
mp.set_start_method('spawn')
main_sleep_period: int = 5
# Spawn a process
process = Process(target=child_operation())
process.start()
# Now do something in main while process is running
logging.info(f'main: sleeping for {main_sleep_period} sec') # XX
time.sleep(main_sleep_period)
logging.info('main stopped sleeping')
process.join()
if __name__ == "__main__":
main()
所以子进程运行了大约10秒。我预计“主”进程中标记为“XX”的行会在子进程启动后不久运行。然而我总是发现这一行出现在子进程完成其操作之后:
2024-08-23 13:32:56,946 2024-08-23 13:32:56.946205: started operation child
2024-08-23 13:32:56,946 operation child, i=0: sleeping for period 1 sec
2024-08-23 13:32:57,946 operation child, i=1: sleeping for period 1 sec
2024-08-23 13:32:58,947 operation child, i=2: sleeping for period 1 sec
2024-08-23 13:32:59,948 operation child, i=3: sleeping for period 1 sec
2024-08-23 13:33:00,949 operation child, i=4: sleeping for period 1 sec
2024-08-23 13:33:01,950 operation child, i=5: sleeping for period 1 sec
2024-08-23 13:33:02,951 operation child, i=6: sleeping for period 1 sec
2024-08-23 13:33:03,952 operation child, i=7: sleeping for period 1 sec
2024-08-23 13:33:04,953 operation child, i=8: sleeping for period 1 sec
2024-08-23 13:33:05,953 operation child, i=9: sleeping for period 1 sec
2024-08-23 13:33:06,954 2024-08-23 13:33:06.954231: ended operation child
2024-08-23 13:33:06,976 main: sleeping for 5 sec
2024-08-23 13:33:11,978 main stopped sleeping
也许您需要将
()
。我的意思是:
process = Process(target=child_operation())
试试这个:
process = Process(target=child_operation)