Python--并发编程--协程

概念

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

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())

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习_程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值