多进程multiprocessing通信multiprocessing.Queue

multiprocessing.Queue` 通常只能在主模块(即 `if name == "main":` 块)中创建和使用。这是因为 `multiprocessing` 模块在 Windows 系统上需要通过 `if name == "main":` 块来避免递归导入问题。

python 复制代码
from multiprocessing import Queue, Process


def work(queue):
    queue.put("我已发送消息到主进程")


if __name__ == "__main__":
    # 实例化一个消息通道
    queue = Queue()
    # 实例化一个进程
    process = Process(target=work, args=(queue,))
    # 启动子进程
    process.start()
    print("主进程等待消息")
    msg = queue.get()
    print("主进程收到消息:", msg)
    process.join()
    print("主进程结束")

当然 你也可以双向通信

python 复制代码
from multiprocessing import Queue, Process


def work(input_queue, output_queue):
    input_queue.put("我已发送消息到主进程")
    msg = output_queue.get()
    print("主进程发送消息已收到", msg)


if __name__ == "__main__":
    # 实例化一个消息通道
    input_queue = Queue()
    output_queue = Queue()
    # 实例化一个进程
    process = Process(target=work, args=(input_queue, output_queue))
    # 启动子进程
    process.start()
    print("主进程等待消息")
    msg = input_queue.get()
    print("主进程收到消息:", msg)
    output_queue.put("这里是主进程发送消息")
    process.join()
    print("主进程结束")

还可持续通信

python 复制代码
from multiprocessing import Queue, Process


def work(input_queue, output_queue):
    while 1:
        msg = output_queue.get()
        print("主进程发送消息已收到", msg)
        if msg == 2:
            input_queue.put("关闭")
            break
        else:
            input_queue.put("子进程已收到消息")


if __name__ == "__main__":
    # 实例化一个消息通道
    input_queue = Queue()
    output_queue = Queue()
    # 实例化一个进程
    process = Process(target=work, args=(input_queue, output_queue))
    # 启动子进程
    process.start()
    print("主进程等待消息")
    while 1:
        try:
            msg = input_queue.get(timeout=1)
        except:
            msg = "666"
        if msg != "关闭":
            if msg != "666":
                print("主进程收到消息:", msg)
            input_msg = int(input("输入数值2退出"))
            output_queue.put(input_msg)
        else:
            print("进程结束")
            break
    process.join()
    print("主进程结束")
相关推荐
林泽毅1 小时前
PyTRIO快速入门(一):概念、推理与训练
人工智能·python·深度学习·机器学习·语言模型
admin and root1 小时前
「移动安全」安卓APP 反编译&frida脱壳技巧分享
android·开发语言·python·web安全·微信小程序·移动安全·攻防演练
雪的季节1 小时前
Python基础5-18
开发语言·python
学术小李1 小时前
基于Pytorch,如何用CUDA自己写算子?(一)
人工智能·pytorch·python
ShirleyWang0122 小时前
让headlamp控制台能访问
linux·服务器·python·k8s·k3s
想会飞的蒲公英2 小时前
用 Streamlit 给文本分类模型做一个演示页面
人工智能·python·机器学习
老徐聊GEO2 小时前
亲测有效的AI品牌检测公司案例分享
大数据·人工智能·python
华研前沿标杆游学3 小时前
2026年企业对标学习TOP7项目:小米数字化考察上榜
python
大模型码小白3 小时前
Spring AI 框架实战:Java 后端集成大模型的架构设计与工程落地
java·人工智能·python·spring
BerryS3N4 小时前
深度解析:从零构建生产级大模型 RAG(检索增强生成)系统全栈指南
开发语言·python·ai