python中利用队列asyncio.Queue进行通讯详解
前言
本文主要给大家介绍了关于python用队列asyncio.Queue通讯的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
asyncio.Queue与其它队列是一样的,都是先进先出,它是为协程定义的
例子如下:
importasyncio
asyncdefconsumer(n,q):
print('consumer{}:starting'.format(n))
whileTrue:
print('consumer{}:waitingforitem'.format(n))
item=awaitq.get()
print('consumer{}:hasitem{}'.format(n,item))
ifitemisNone:
#Noneisthesignaltostop.
q.task_done()
break
else:
awaitasyncio.sleep(0.01*item)
q.task_done()
print('consumer{}:ending'.format(n))
asyncdefproducer(q,num_workers):
print('producer:starting')
#Addsomenumberstothequeuetosimulatejobs
foriinrange(num_workers*3):
awaitq.put(i)
print('producer:addedtask{}tothequeue'.format(i))
#AddNoneentriesinthequeue
#tosignaltheconsumerstoexit
print('producer:addingstopsignalstothequeue')
foriinrange(num_workers):
awaitq.put(None)
print('producer:waitingforqueuetoempty')
awaitq.join()
print('producer:ending')
asyncdefmain(loop,num_consumers):
#Createthequeuewithafixedsizesotheproducer
#willblockuntiltheconsumerspullsomeitemsout.
q=asyncio.Queue(maxsize=num_consumers)
#Scheduledtheconsumertasks.
consumers=[
loop.create_task(consumer(i,q))
foriinrange(num_consumers)
]
#Scheduletheproducertask.
prod=loop.create_task(producer(q,num_consumers))
#Waitforallofthecoroutinestofinish.
awaitasyncio.wait(consumers+[prod])
event_loop=asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(event_loop,2))
finally:
event_loop.close()
输出如下:
consumer0:starting consumer0:waitingforitem consumer1:starting consumer1:waitingforitem producer:starting producer:addedtask0tothequeue producer:addedtask1tothequeue consumer0:hasitem0 consumer1:hasitem1 producer:addedtask2tothequeue producer:addedtask3tothequeue consumer0:waitingforitem consumer0:hasitem2 producer:addedtask4tothequeue consumer1:waitingforitem consumer1:hasitem3 producer:addedtask5tothequeue producer:addingstopsignalstothequeue consumer0:waitingforitem consumer0:hasitem4 consumer1:waitingforitem consumer1:hasitem5 producer:waitingforqueuetoempty consumer0:waitingforitem consumer0:hasitemNone consumer0:ending consumer1:waitingforitem consumer1:hasitemNone consumer1:ending producer:ending
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。