zoukankan      html  css  js  c++  java
  • 线程_进程间通信Queue合集

    # Queue的工作原理
    from multiprocessing import Queue
    q = Queue(3)#初始化一个Queue对象,最多可接收3条put消息
    q.put("Info1")
    q.put("Info2")
    print("q是否满了",q.full())#查看q是否满了
    q.put("Info3")
    print("q是否满了",q.full())
    try:
        q.put_nowait("info4")
    except:
        print("消息列队已经满了,现有消息数量为:%s"%(q.qsize()))
        # 使用q.qsize()查看数量
    # 先验证是否满了,再写入
    if not q.full():
        q.put_nowait("info4")
    # 读取信息时,先判断消息列队是否为空,再读取
    
    if not q.empty():
        print("开始读取")
        for i in range(q.qsize()):
            print(q.get_nowait())

    from multiprocessing import Queue
    from multiprocessing import Process
    import os,time,random
    
    def  write(q):
        for value in ['a','b','c']:
            print("Put %s to q ..."%(value))
            q.put(value)
            time.sleep(random.random())
    
    def read(q):
        while True:
            if not q.empty():
                value = q.get(True)
                print("Get %s from Queue..."%(value))
                time.sleep(random.random())
            else:
                break
    
    if __name__ == '__main__':
        #父进程创建Queue,传给各个子进程
        q = Queue()
        pw = Process(target=write,args=(q,))
        pr = Process(target=read,args=(q,))
        pw.start()
        # 等待pw结束
        pw.join()
        pr.start()
        pr.join()
        print("数据写入读写完成")

    from multiprocessing import Manager,Pool
    import os,time,random
    # 名称为reader 输出子进程和父进程 os  输出q的信息
    
    def reader(q):
        print("reader启动,子进程:%s,父进程:%s"%(os.getpid(),os.getppid()))
        for i in range(q.qsize()):#在0 ~ qsize范围内
            print("获取到queue的信息:%s"%(q.get(True)))
    
    def writer(q):
        print("writer启动,子进程:%s,父进程:%s"%(os.getpid(),os.getppid()))
        for i in "HanYang":#需要写入到 q 的数据
            q.put(i)
    
    if __name__ == '__main__':
        print("%s 开始 "%(os.getpid()))
        q = Manager().Queue()#Queue使用multiprocessing.Manager()内部的
        po = Pool()#创建一个线程池
        po.apply(writer,(q,))#使用apply阻塞模式
        po.apply(reader,(q,))
        po.close()#关闭
        po.join()#等待结束
        print("(%s) 结束"%(os.getpid()))

    2020-05-07

  • 相关阅读:
    「酷客多」关注:马化腾公开演讲,透露2017年春节前会推出“小程序”
    微信小程序购物商城系统开发系列-目录结构
    微信小程序购物商城系统开发系列-工具篇
    上海闪酷成为京东商城第一批独立软件开发商(ISV)
    【FFMPEG】关于硬解码和软解码
    Git 别名配置
    【Linux】扩展阿里云数据盘分区和文件系统
    Python实现MQTT接收订阅数据
    【Linux】Devops的一些运维工具
    【Linux】YUM Repositories for CentOS, RHEL & Fedora Systems
  • 原文地址:https://www.cnblogs.com/hany-postq473111315/p/12845662.html
Copyright © 2011-2022 走看看