After Python3.5, it is very easy to implement coroutines because we provide field await and async, and we no longer need to use decorators to write coroutines in asyncio. However, we often need to use queues in programs, but asyncio provides special methods. This makes it very simple to use, using put and GET to manipulate queues. Here’s an example:
The import asyncio async def make_tea (num: int, data: asyncio. Queue) : for I in range (num) : print (' first {} is making a cup of milk tea! '.format(I + 1)) await data.put(I) await asyncio.sleep(1)# similar to ordinary function time.sleep(1) print(' {} cup milk tea already sold! '.format(i+1)) async def drink_tea(num:int,data:asyncio.Queue): count=0 while count<num: Format (content+1)) count+=1 data= asyncio.queue ()# Loop =asyncio.get_event_loop() task1=loop.create_task(make_tea(10,data) Task2 =loop.create_task(drink_tea(10,data))# Create a new task. Tasks = Asyncio. Gather (task1,task2 loop.run_until_complete(tasks)Copy the code
We can look at the result of the run:
The first cup of milk tea is being made! Drinking the first cup of milk tea the first cup of milk tea is sold! The 2nd cup of milk tea is being made! Drinking the second cup of milk tea the second cup of milk tea has been sold! The third cup of milk tea is being made! Drinking the 3rd cup of milk tea the 3rd cup of milk tea is sold! The fourth cup of milk tea is being made! Drinking the fourth cup of milk tea the fourth cup of milk tea has been sold! The fifth cup of milk tea is being made! Drinking the fifth cup of milk tea the fifth cup of milk tea is sold! The sixth cup of milk tea is being made! Drinking the sixth cup of milk tea the sixth cup of milk tea has been sold! The seventh cup of milk tea is being made! Drinking the seventh cup of milk tea the seventh cup of milk tea is sold! The eighth cup of milk tea is being made! Drinking the 8th cup of milk tea the 8th cup of milk tea is sold! The ninth cup of milk tea is being made! Drinking the ninth cup of milk tea the ninth cup of milk tea has been sold! The 10th cup of milk tea is being made! Drinking the tenth cup of milk tea the tenth cup of milk tea has been sold!Copy the code
This makes it easy to use the queue, but it is important to note that the queue is infinite by default. Normal queue use requires that the queue size be specified, and the coroutine cannot get the queue size. Sleep (1) and await data.put(I) are both running at the same time, but asyncio.sleep(1) is running longer, so next sentence is run.