惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Project Zero
Project Zero
S
Security @ Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
A
Arctic Wolf
Webroot Blog
Webroot Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Security Latest
Security Latest
H
Heimdal Security Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
T
Tor Project blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
The Last Watchdog
The Last Watchdog
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
A
About on SuperTechFans
M
MIT News - Artificial intelligence
V
V2EX
V
Visual Studio Blog
Recorded Future
Recorded Future
博客园 - 叶小钗
F
Fortinet All Blogs
L
Lohrmann on Cybersecurity
The GitHub Blog
The GitHub Blog
博客园 - Franky
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Secure Thoughts
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)
I
InfoQ
SecWiki News
SecWiki News
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
B
Blog RSS Feed
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
V
Vulnerabilities – Threatpost
H
Help Net Security

Liu Zijian's Blog | 一个技术博客

使用Certbot自动续签HTTPS证书 使用Filebeat采集Nginx日志到ES Python中的异常 Python中的类和对象 Python的函数 Python的数据结构,推导式、迭代器和生成器 Spring AI集成多模态模型 LangChain4j多模态 LangChain Tools工具使用 Python中的模块和包 Python全局环境和虚拟环境(venv) LangChain Prompt提示词工程 LangChain4j Tools工具使用 基于Dify搭建AI智能体应用 LangChain4j RAG检索增强生成 Spring AI实现MCP Server Spring AI集成MCP Client LangChain4j Prompt提示词工程 Spring AI使用知识库增强对话功能 Spring AI实现一个智能客服 Spring AI实现一个简单的对话机器人 实现MinIO数据的每日备份 自己实现一个DNS服务 简单理解AI智能体 大模型和大模型应用 LangChain开篇 LangChain4j开篇 一个解析Excel2007的POI工具类 DataPermissionInterceptor源码解读 TenantLineInnerInterceptor源码解读 BaseMultiTableInnerInterceptor源码解读 Spring AI开篇 SQL解析工具JSQLParser 芋道源码解读之多租户 芋道源码解读之数据权限 芋道源码解读开篇 Java实现将数据导出为Word文档 OA系统的天数该怎样计算 安装MySQL8 安装MySQL5.7 RockyLinux9环境下编译MySQL8 MySQL字符集及底层原理 Java实现LDAP登录 Docker Compose IPv4和IPv6 使用虚拟机安装一个K8s集群 使用GraalVM原生编译打包SpringBoot工程 Nginx防止目录穿越 Java线程的状态 Nginx防盗链设置 使用python将excel表格转换为SQL INSERT Redis的公共操作命令 Redis数据结构之Bitfleid Redis数据结构之Bitmap Redis数据结构之GEO Redis数据结构之Hash Redis数据结构之HyperLogLog Redis数据结构之List Redis数据结构之Set Redis数据结构之Stream Redis数据结构之String Redis数据结构之ZSet 使用python压缩图片 利用Python实现Hexo站点的持续集成 Nginx设置HTTPS监听 firewalld防火墙工具的使用 Linux信号(signal)机制 MySQL5.7x 主从复制 用IP自签发一个HTTPS证书 基于Hexo实现一个静态的个人博客 RockyLinux9环境下编译MySQL5.7 Docker离线安装 MySQL数据定义语言 Docker与联合文件系统 Docker的网络 Docker的镜像操作 MySQL存储过程 MyBatis-Plus开篇 MySQL变量 MySQL视图 MySQL事务 MySQL插入修改和删除 MySQL查询 MySQL系统命令 Docker的容器操作 Docker的安装和配置 Docker容器数据卷 浅谈OAuth2.0授权原理 JVM开篇 浅谈Linux(Unix)的I/O模型 一个通用的CloseableHttpClient工厂类 JUC可重入锁ReentrantLock JUC读写锁ReadWriteLock Java的单例 Java泛型 Java8的新特性 最近最少使用算法(LRU) MySQL函数 SpringBoot配置和启动 volatile作用分析
Python的协程
Liu Zijian · 2026-03-22 · via Liu Zijian's Blog | 一个技术博客

未完待续

1.协程

协程(coroutine),又叫微线程或虚拟线程,是一种用户态的上下文切换技术,python中的协程,是通过一种可以被挂起,并且挂起后还能恢复执行的函数来实现的

某些操作会造成当前线程CPU发生阻塞,比如I/O操作,I/O操作不需要当前线程执行,但是当前线程提交了操作后也要白白等待一段时间拿到数据,才能继续执行,之前可以使用多线程来同时进行多路I/O操作,让子线程阻塞,主线程干些别的,而协程可以实现的就是让单个线程进行多路I/O操作时,也可以不需等待。

python中,协程可将多路I/O操作拆为多个方法,每个方法执行一路,事件循环实时监测各个方法状态,哪个方法阻塞了,事件循环迅速切换其他不阻塞的方法继续执行,而且这一切都发生在一个线程内。

2.async和协程函数

在python中,将一个普通函数加上async关键字,就会变成一个协程函数,执行协程函数,函数本身不会被调用,而是直接返回一个协程(coroutine )对象

async def a():
    print('a')
    return 1

async def b():
    print('b')
    return 2

task1 = a()
task2 = b()

if __name__ == "__main__":
    print(task1)
    print(task2)
<coroutine object a at 0x000001D4A91E5A80>
<coroutine object b at 0x000001D4A91E59C0>
<sys>:0: RuntimeWarning: coroutine 'a' was never awaited
<sys>:0: RuntimeWarning: coroutine 'b' was never awaited

3.asyncio和await

要使得协程函数执行,需要asyncio.run()来调用协程函数,asyncio的原理,是将协程函数包装成任务,交给事件循环,事件循环就是一个死循环,不断轮询检查管理的协程函数的状态,发现谁阻塞了,立即将执行权拿走,交给其他未阻塞的协程函数继续执行当前线程

协程函数的返回值,也是从asyncio.run()的调用拿到

import asyncio

async def a():
    print('a')
    return 1

task1 = a()

if __name__ == "__main__":
    r = asyncio.run(task1)
    print(r)
a
1
<sys>:0: RuntimeWarning: coroutine 'b' was never awaited

await对于python协程非常重要,关系着协程是否真正实现

事件循环基于await判断程序是否阻塞,遇到await后接的是需要等待的操作,CPU控制权便交给了事件循环,await后面的代码执行的同时,事件循环也会将执行权拿走,交给其他未阻塞的协程函数继续执行当前线程(如果有的话)

如果协程函数中没有await一个需要等待的操作,事件循环永远不会得到CPU控制权,当前函数一直执行下去,其他未阻塞的协程函数也不会得到执行权

await后面只能接可等待的对象:Future,其他协程函数,Task。

await只能出现在async修饰的函数中,这是python语法的规定。


例:协程函数中没有await一个需要等待的b(),b()执行完才会跳出继续执行a()

import asyncio

async def a():
    print('a before')
    await b()
    print('a after')
    return 1

async def b():
    print('b')
    return 2

task1 = a()

if __name__ == "__main__":
    r = asyncio.run(task1)
    print(r)
a before
b
a after
1

例:协程函数中await了一个需要等待的b(),b()执行asyncio.sleep(5)模拟阻塞,但是因为事件循环中只是asyncio.run(task1)了一个task1任务,因此仍然是继续等待b()执行完成

import asyncio

async def a():
    print('a before')
    await b()
    print('a after')
    return 1

async def b():
    print('b')
    await asyncio.sleep(5)
    return 2

task1 = a()

if __name__ == "__main__":
    r = asyncio.run(task1)
    print(r)
a before
b
a after
1

例:多任务同步执行:协程方法main()中,启动其他三个协程方法,但是事件循环中只管理一个main(),因此三个协程方法a,b,c之一出现阻塞时,事件循环不会转移执行权到另两个。

import asyncio

async def a():
    print('a')
    await asyncio.sleep(5)
    return 1

async def b():
    print('b')
    await asyncio.sleep(5)
    return 2

async def c():
    print('c')
    await asyncio.sleep(5)
    return 2

async def main():
    task1 = a()
    task2 = b()
    task3 = c()

    await task1 
    await task2 
    await task3

if __name__ == "__main__":
    print('start')
    asyncio.run( main() )
    print('end')
start
a
b
c
end

上述,都是不涉及事件循环切换任务的同步执行,实际场景使用更多的是涉及事件循环切换的异步执行

例:通过asyncio.create_task()方法,可以将协程函数包装为可以被事件循环调度的任务,并注册到事件循环中,main()a(),b(),c()先后加入到事件循环

main()本身也是这个协程中的一环,其中三个函数执行或挂起,会导致它作为一个“容器”也被挂起,只有三个函数都执行完,main()才会继续

import asyncio

async def a():
    print('a before')
    await asyncio.sleep(5)
    print('a after')
    return 1

async def b():
    print('b before')
    await asyncio.sleep(5)
    print('b after')
    return 2

async def c():
    print('c before')
    await asyncio.sleep(5)
    print('c after')
    return 2

async def main():
    task1 = asyncio.create_task( a() )
    task2 = asyncio.create_task( b() )
    task3 = asyncio.create_task( c() )
    # 加入事件循环后,启动
    v1 = await task1
    v2 = await task2
    v3 = await task3
    
    print(v1)
    print(v2)
    print(v3)

if __name__ == "__main__":
    print('start')
    asyncio.run( main() )
    print('end')
start
a before
b before
c before
a after
b after
c after
1
2
2
end

写一堆await总是很繁琐的,还可以通过asyncio.gather()将多个协程对象同时注入事件循环,并在全部执行完成后,一次性拿到所有结果

import asyncio

async def a():
    print('a before')
    await asyncio.sleep(5)
    print('a after')
    return 1

async def b():
    print('b before')
    await asyncio.sleep(5)
    print('b after')
    return 2

async def c():
    print('c before')
    await asyncio.sleep(5)
    print('c after')
    return 2

async def main():
    res = await asyncio.gather(a(), b(), c())
    print(res)

if __name__ == "__main__":
    print('start')
    asyncio.run( main() )
    print('end')
start
a before
b before
c before
a after
b after
c after
[1, 2, 2]
end