栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python消息队列Queue

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python消息队列Queue

实例1:消息队列Queue,不要将文件命名为“queue.py”,否则会报异常“importError: cannot import name 'Queue'”

1234567891011121314151617181920212223242526272829#coding=utf-8from multiprocessing import Queue  Queue(3)#初始化一个Queue对象,最多可接收三条put消息q.put('message-1')q.put('message-2')print(q.full())#False,是否满了q.put('message-3')print(q.full())#True #因为消息队列已满,下面的try都会抛出异常,第一个try会等待2秒后再抛出异常,第二个try会立即抛出异常try:    q.put('message-4',True,2)except:    print('except1,消息队列已满,现有消息数量:%s'%q.qsize()) try:    q.put_nowait('message-4')except:    print('except2,消息队列已满,现有消息数量:%s'%q.qsize()) #判断队列是否已满if not q.full():    q.put_nowait('message-4'#读取消息时,先判断消息队列是否为空,在读取if not q.empty():    for in range(q.qsize()):        print(q.get())#q.get会阻塞,q.get_nowait()不阻塞,但会抛异常                   

False

True

except1,消息队列已满,现有消息数量:3

except2,消息队列已满,现有消息数量:3

message-1

message-2

message-3


实例二:通过Process进程间通信

123456789101112131415161718192021222324252627282930313233from multiprocessing import Process,Queueimport os,time,random  #写数据def write(q):    for value in ['A','B','C']:        print('Put %s to queue...'%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__':    print('start...')    Queue()    #父进程的queue传递给子进程    pw Process(target=write,args=(q,))    pr Process(target=read,args=(q,))                   #写进程    pw.start()    pw.join()    #读进程    pr.start()    pr.join()    print('done...')

start...

Put A to queue...

Put B to queue...

Put C to queue...

Get A from queue...

Get B from queue...

Get C from queue...

done...


实例三:通过Manager进程间通信

123456789101112131415161718192021222324252627from multiprocessing import Manager,Poolimport os,time,random  #写数据def writer(q):    print('writer启动(%s),父进程为(%s)'%(os.getpid(),os.getppid()))    for in 'chaoge':        q.put(i) #读数据def reader(q):    print('reader启动(%s),父进程为(%s)'%(os.getpid(),os.getppid()))    for in range(q.qsize()):        print('reader 从Queue获取到消息:%s'%q.get())  if __name__ ='__main__':    print('(%s) start'%os.getpid())    Manager().Queue()#使用Manager中的Queue来初始化    po=Pool()    #使用阻塞模式创建进程,这样就不需要再reader中使用死循环了,可以等write执行完成后,再用reader    po.apply(writer,(q,))    po.apply(reader,(q,))    #写进程    po.close()    po.join()    print('(%s) End'%os.getpid())

(7720) start

writer启动(7284),父进程为(7720)

reader启动(8712),父进程为(7720)

reader 从Queue获取到消息:c

reader 从Queue获取到消息:h

reader 从Queue获取到消息:a

reader 从Queue获取到消息:o

reader 从Queue获取到消息:g

reader 从Queue获取到消息:e

(7720) End


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/223646.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号