Python 3 中的协程是异步编程的一种形式,它允许您在代码中创建可暂停的函数,以便其他任务可以运行,而不会阻塞程序的执行。async/await 是 Python 3.5 之后引入的语法,用于编写协程。
下面是一些协程和 async/await 的用法示例:
1.使用 async 关键字定义协程函数
import asyncio
async def my_coroutine():
print('Coroutine started')
await asyncio.sleep(1)
print('Coroutine ended')
loop = asyncio.get_event_loop()
loop.run_until_complete(my_coroutine())
上面的代码定义了一个协程函数 my_coroutine(),它在开始时打印一条消息,等待 1 秒钟,然后打印另一条消息。我们使用 asyncio.sleep() 函数来模拟延迟。
2.使用 asyncio.gather() 并行运行多个协程
import asyncio
async def coroutine_one():
print('Coroutine one started')
await asyncio.sleep(1)
print('Coroutine one ended')
async def coroutine_two():
print('Coroutine two started')
await asyncio.sleep(2)
print('Coroutine two ended')
async def main():
tasks = [coroutine_one(), coroutine_two()]
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
上面的代码定义了三个协程函数:coroutine_one()、coroutine_two() 和 main()。main() 函数并行运行 coroutine_one() 和 coroutine_two() 协程函数,我们使用 asyncio.gather() 函数来等待所有协程完成。
3.使用 asyncio.Queue() 传递消息
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:857662006
import asyncio
async def producer(queue):
print('Producer started')
for i in range(5):
await asyncio.sleep(1)
await queue.put(i)
await queue.put(None)
print('Producer ended')
async def consumer(queue):
print('Consumer started')
while True:
item = await queue.get()
if item is None:
queue.task_done()
break
print(f'Consumed {item}')
await asyncio.sleep(0.5)
queue.task_done()
print('Consumer ended')
async def main():
queue = asyncio.Queue()
producer_task = asyncio.create_task(producer(queue))
consumer_task = asyncio.create_task(consumer(queue))
await asyncio.gather(producer_task)
await queue.join()
await consumer_task
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
上面的代码定义了三个协程函数:producer()、consumer() 和 main()。producer() 协程函数将数字放入队列中,并在最后放置一个 None,以表示它已经完成了它的工作。consumer() 协程函数从队列中获取项目并打印它们,直到它遇到 None。main() 函数创建了一个队列,运行了 producer() 和 consumer() 协程函数,并使用 asyncio.gather() 函数等待 producer() 完成。当队列为空时,我们使用 await queue.join() 等待所有项目被处理。最后,我们等待 consumer() 协程函数完成。
这些示例只是一些使用 async/await 实现协程的简单示例,您可以根据需要修改和扩展它们。