多进程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("主进程结束")
相关推荐
Halo_tjn28 分钟前
Set集合专项实验
java·开发语言·前端·python
vvoennvv1 小时前
【Python TensorFlow】 BiTCN-LSTM双向时间序列卷积长短期记忆神经网络时序预测算法(附代码)
python·神经网络·tensorflow·lstm·tcn
q***42051 小时前
python的sql解析库-sqlparse
数据库·python·sql
大数据追光猿2 小时前
LangChain / LangGraph / AutoGPT / CrewAI / AutoGen 五大框架对比
经验分享·笔记·python·langchain·agent
wang_yb2 小时前
别急着转投 Polars!Pandas 3.0 带着“黑科技”杀回来了
python·databook
Jamesvalley2 小时前
flask处理所有logging
后端·python·flask
ekprada2 小时前
DAY 16 数组的常见操作和形状
人工智能·python·机器学习
柳鲲鹏2 小时前
OpenCV: 光流法python代码
人工智能·python·opencv
databook3 小时前
别急着转投 Polars!Pandas 3.0 带着“黑科技”杀回来了
后端·python·数据分析
烟袅3 小时前
为什么调用 OpenAI Tools 后,还要再请求一次大模型?——从代码看 LLM 工具调用的本质
后端·python·llm