多进程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("主进程结束")
相关推荐
数据智能老司机7 分钟前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i2 小时前
django中的FBV 和 CBV
python·django
c8i2 小时前
python中的闭包和装饰器
python
这里有鱼汤5 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩15 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在20 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python