📅  最后修改于: 2023-12-03 15:34:26.100000             🧑  作者: Mango
协程(Coroutine)是指一种程序组件,协程可以在其执行期间挂起,让其它协程执行。协程也被称为用户级线程或轻量级线程,它的运行由用户自己控制。
在Python中,通过asyncio
模块实现了协程。下面将介绍Python中的协程及其使用。
定义协程可以使用async def
关键字来定义一个协程函数。在协程函数中,可以使用await
关键字来挂起当前协程的执行,并等待另一个协程或异步调用的结果返回。
以下是一个简单的协程函数示例:
import asyncio
async def foo():
print("start foo")
await asyncio.sleep(1)
print("end foo")
async def main():
print("start main")
await foo()
print("end main")
asyncio.run(main())
该程序中,定义了两个协程函数foo
和main
。在main
函数中调用了foo
函数,并使用await
关键字等待foo
函数的执行结果。程序输出如下:
start main
start foo
end foo
end main
由输出可知,程序按照预期执行。
在Python中,协程的调度是由asyncio
模块实现的。在调度过程中,使用asyncio
模块提供的事件循环机制来调度协程的执行。
以下是一个简单的协程调度示例:
import asyncio
async def foo():
print("start foo")
await asyncio.sleep(1)
print("end foo")
async def main():
print("start main")
task = asyncio.create_task(foo())
await task
print("end main")
asyncio.run(main())
可以看到,在调用foo
函数时,使用asyncio.create_task
函数创建一个任务,并使用await
关键字等待任务执行完成。
在Python中,协程的并发可以由asyncio.gather
函数实现。该函数可以等待多个协程同时执行完成,并返回每一个协程的执行结果。
以下是一个简单的协程并发示例:
import asyncio
async def foo():
print("start foo")
await asyncio.sleep(1)
print("end foo")
return "foo"
async def bar():
print("start bar")
await asyncio.sleep(1)
print("end bar")
return "bar"
async def main():
print("start main")
results = await asyncio.gather(foo(), bar())
print("end main ->", results)
asyncio.run(main())
在该程序中,调用了两个协程函数foo
和bar
,在main
函数中使用asyncio.gather
函数等待两个协程函数并发执行,最后输出执行结果。
在协程执行过程中,可能会发生超时等异常情况。在Python中,可以使用asyncio.wait_for
函数实现协程的超时控制。
以下是一个简单的协程超时示例:
import asyncio
async def foo():
print("start foo")
await asyncio.sleep(2)
print("end foo")
return "foo"
async def main():
print("start main")
try:
result = await asyncio.wait_for(foo(), timeout=1)
print("result ->", result)
except asyncio.TimeoutError:
print("timeout")
print("end main")
asyncio.run(main())
在该示例中,foo
函数的执行时间为2秒,而在main
函数中设置了1秒的超时时间,当执行时间超过1秒时,会抛出asyncio.TimeoutError
异常,并输出timeout
。
以上是Python中协程的基础用法,了解了协程的基础用法后,可以更深入地使用协程来实现异步编程,提高程序的性能和响应速度。