多进程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("主进程结束")
相关推荐
ShCDNay7 分钟前
Python核心底层知识(个人记录)
开发语言·python
来自远方的老作者19 分钟前
第7章 运算符-7.2 赋值运算符
开发语言·数据结构·python·赋值运算符
来自远方的老作者37 分钟前
第7章 运算符-7.1 算术运算符
开发语言·数据结构·python·算法·算术运算符
tq6J5Yg1440 分钟前
windows10本地部署openclaw
前端·python
pl4H522a61 小时前
Python 高效实现 Excel 转 TXT 文本
java·python·excel
数据知道1 小时前
claw-code 源码详细分析:Compaction 前置课——上下文压缩在接口层要预留哪些旋钮,避免后期全局返工?
python·ai·claude code
小邓睡不饱耶1 小时前
花店花品信息管理系统开发实战:Python实现简易门店管理系统
服务器·python·microsoft
witAI2 小时前
手机生成剧本杀软件2025推荐,创新剧情设计工具助力创作
人工智能·python
派大星~课堂2 小时前
【力扣-138. 随机链表的复制 ✨】Python笔记
python·leetcode·链表
王忘杰2 小时前
0基础CUDA炼丹、增加断点保存,从零开始训练自己的AI大模型 87owo/EasyGPT Python CUDA
开发语言·人工智能·python