Python--并发编程--协程

发布于:2024-07-10 ⋅ 阅读:(136) ⋅ 点赞:(0)

概念

协程是轻量级的线程,它是程序员管理的并发机制,使得在一个线程中程序可以在多个函数之间交替运行。

Python中主要通过asyncio模块实现协程。

协程函数

async修饰的函数

import asyncio

# func为协程函数
async def func():
    await asyncio.sleep(1)

协程对象

协程函数的调用结果 。

需要注意的是,此时并不会执行协程函数的内部代码。

# 协程对象
func()

可等待对象

await关键词修饰的对象,包括协程对象task对象future对象

创建协程

通过asyncio.run(协程对象)方法运行协程函数时,协程之间是同步阻塞的。

import asyncio
import time

async def func(i):
    print(f'func {i} started...')
    await asyncio.sleep(2)
    print(f'func {i} ended...')

print(time.strftime('%Y/%m/%d %H:%M:%S'))
asyncio.run(func(1))
asyncio.run(func(2))

print(time.strftime('%Y/%m/%d %H:%M:%S'))

通过asyncio.create_task(协程对象)方法运行多个协程函数时 ,协程之间是异步非阻塞的。

import asyncio
import time

async def func(i):
    print(f'func {i} started...')
    await asyncio.sleep(2)
    print(f'func {i} ended...')

print(time.strftime('%Y/%m/%d %H:%M:%S'))

async def main():
    task1 = asyncio.create_task(func(1))
    task2 = asyncio.create_task(func(2))
    await task2
    await task1

asyncio.run(main())
print(time.strftime('%Y/%m/%d %H:%M:%S'))

简单等待

通过asyncio.wait(可等待对象,return_when=ALL_COMPLETED)方法并发运行可等待对象,并进入阻塞状态直到满足return_when指定的条件。

  • 返回两个一个元组(done, pending)
    • done代表完成的task集合
    • pending代表未完成的task集合
  • return_when表示wait函数啥时候返回结果
    • FIRST_COMPLETED: 有一个可等待对象完成时
    • FIRST_EXCEPTION: 有一个异常发生时
    • ALL_COMPLETED: 所有可等待对象都完成时
import asyncio
import time


async def say(greeting, seconds):
    await asyncio.sleep(seconds)
    print(greeting)

async  def main():

    say_hi = say('hi', 1)
    say_hello = say('hello', 2)
    task_hi = asyncio.create_task(say_hi)
    task_hello = asyncio.create_task(say_hello)
    print(time.strftime('%Y/%m/%d %H:%M:%S'))
    done, pending = await asyncio.wait([task_hi, task_hello])
    print(time.strftime('%Y/%m/%d %H:%M:%S'))
    print(done)

asyncio.run(main())


网站公告

今日签到

点亮在社区的每一天
去签到