多进程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("主进程结束")
相关推荐
NullPointer819 分钟前
【剪映小助手源码精讲】第39章:CI流程
python·aigc
七夜zippoe21 分钟前
Python并发与并行编程深度剖析:从GIL原理到高并发实战
服务器·网络·python·并发·gil
weixin_4573402126 分钟前
lora监督微调(SFT)
开发语言·python
weixin_3903084632 分钟前
Jenkins报Host key verification failed错误
python·jenkins
码农三叔41 分钟前
(4-2-05)Python SDK仓库:MCP服务器端(5)Streamable HTTP传输+Streamable HTTP传输
开发语言·python·http·大模型·1024程序员节·mcp·mcp sdk
IT枫斗者1 小时前
Spring Boot 4.0 正式发布:新一代起点到底“新”在哪?(Spring Framework 7 / Java 25 / JSpecify / API 版本管理 / HTTP Service
java·开发语言·spring boot·后端·python·spring·http
AI大佬的小弟1 小时前
Python基础(10):Python函数基础详解
开发语言·python·函数·ai大模型基础·嵌套函数·变量的作用域·全局变量和局部变量
SZ1701102311 小时前
N-S图 (盒图) N-S图是“盒子嵌套”,PAD图是“树干分叉”*
python
智航GIS1 小时前
8.5 os 模块
python
njsgcs1 小时前
blender内部python调用 cats-blender-plugin 导入模型
python·blender