You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让带While True无限循环的Python程序实现并行运行?

多进程实时数据交互实现方案

你之前的误解在于没用到合适的**进程间通信(IPC)**机制——多进程/多线程完全支持在循环中实时传递数据,以下是几种适配你场景的可行技术:

1. 队列(Queue)—— 最易用的IPC方式

Python的multiprocessing.Queue是线程/进程安全的,目标检测进程可持续将检测结果存入队列,主进程在while True循环中实时取数,发现指定目标就执行对应指令。

示例代码:

import multiprocessing
import time

def target_detection(queue):
    # 模拟目标检测循环
    while True:
        # 替换为实际检测逻辑,返回检测结果
        detected_target = "person"  # 示例:检测到行人
        queue.put(detected_target)
        time.sleep(0.5)  # 模拟检测耗时

if __name__ == "__main__":
    result_queue = multiprocessing.Queue()
    # 启动检测进程
    detection_process = multiprocessing.Process(target=target_detection, args=(result_queue,))
    detection_process.start()

    # 主进程循环处理
    while True:
        if not result_queue.empty():
            target = result_queue.get()
            if target == "person":
                print("执行指定指令:发现行人,触发告警")
                # 此处编写你的业务逻辑
        time.sleep(0.1)  # 避免过度占用CPU

2. 管道(Pipe)—— 支持双向通信

multiprocessing.Pipe可实现进程间双向通信,适合需要主进程给检测进程发控制信号(如暂停检测)的场景,单向传数逻辑和队列类似。

示例代码片段:

import multiprocessing
import time

def target_detection(conn):
    while True:
        detected_target = "car"  # 模拟检测结果
        conn.send(detected_target)
        time.sleep(0.5)

if __name__ == "__main__":
    parent_conn, child_conn = multiprocessing.Pipe()
    p = multiprocessing.Process(target=target_detection, args=(child_conn,))
    p.start()

    while True:
        if parent_conn.poll():  # 检查是否有数据待接收
            target = parent_conn.recv()
            if target == "car":
                print("执行指定指令:发现车辆,开启监控录制")
        time.sleep(0.1)

3. 共享内存(Shared Memory)—— 低延迟场景适配

如果检测数据量小(如仅需标记是否检测到目标),可使用multiprocessing.Value或Array共享简单数据类型,实现极低延迟的状态同步。

示例代码:

import multiprocessing
import time

def target_detection(flag):
    while True:
        # 模拟检测到目标的周期
        flag.value = 1  # 1表示检测到指定目标,0表示未检测到
        time.sleep(1)
        flag.value = 0
        time.sleep(2)

if __name__ == "__main__":
    # 创建共享整数(模拟布尔标记)
    detected_flag = multiprocessing.Value('i', 0)
    p = multiprocessing.Process(target=target_detection, args=(detected_flag,))
    p.start()

    while True:
        if detected_flag.value == 1:
            print("执行指定指令:目标出现,启动动作")
            detected_flag.value = 0  # 重置标记避免重复触发
        time.sleep(0.1)

关键注意事项

  • 队列、管道自带线程/进程安全机制,无需额外加锁;共享内存需注意同步,必要时用multiprocessing.Lock避免竞态条件。
  • 目标检测属于CPU密集型任务时,优先用多进程(规避GIL限制);若为IO密集型(如等待摄像头流),多线程也可,但多进程兼容性更强。
  • 主进程结束前需调用process.join()或处理子进程退出逻辑,防止产生僵尸进程。

内容的提问来源于stack exchange,提问作者Qadrillah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:05:40