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

相关推荐

  1. python 异步编程

    2024-07-10 17:06:01       15 阅读
  2. Golang并发编程-goroutine初体验

    2024-07-10 17:06:01       16 阅读
  3. Python异步编程:魔法的快舞

    2024-07-10 17:06:01       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 17:06:01       5 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 17:06:01       5 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 17:06:01       4 阅读
  4. Python语言-面向对象

    2024-07-10 17:06:01       5 阅读

热门阅读

  1. HarmonyOS应用开发前景及使用工具

    2024-07-10 17:06:01       7 阅读
  2. JVM的基础介绍(1)

    2024-07-10 17:06:01       9 阅读
  3. 开源项目编译harbor arm架构的包 —— 筑梦之路

    2024-07-10 17:06:01       13 阅读
  4. 用户特征和embedding层做Concatenation

    2024-07-10 17:06:01       12 阅读