并发运行python子进程好像不是并发

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

我的任务是更新当前作为单个进程运行的现有 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

我想我正在做一些愚蠢的事情。我尝试在谷歌上搜索示例,但我看到的示例仅显示多个子进程如何同时运行,而不显示我们拥有主进程和子进程以及它们如何相互作用的示例。
有人可以指出我的错误吗?

也许您需要将
python concurrency python-multiprocessing
1个回答
0
投票
作为可调用对象传递,而不需要

()。我的意思是:

而不是这个:

process = Process(target=child_operation())
  • 试试这个:
    process = Process(target=child_operation)
  • 让我们看看进展如何

© www.soinside.com 2019 - 2024. All rights reserved.