Skip to content

Commit e7d8974

Browse files
committed
update: asyncio 02 part 2
1 parent a7f2210 commit e7d8974

File tree

32 files changed

+1233
-126
lines changed

32 files changed

+1233
-126
lines changed

content/posts/2025-11-19_python-asyncio-01.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ tags = ['Python', 'Asyncio']
1919

2020
一个 coroutine 协程是一种方法,协程是一种方法,当遇到可能长时间运行的任务时,它可以暂停执行,并在任务完成后恢复执行。
2121

22-
asyncio 这个库的名称可能让人人为其只适合编写 I/O 操作,但实际上该库可以和 multithreading 和 multiprocessing 库结合使用。
22+
asyncio 这个库的名称可能让人人为其只适合编写 I/O 操作,但实际上该库可以和 threading 和 multiprocessing 库结合使用。
2323
基于这种 interoperability 互操作性,可以使用 async/await 关键字让工作流更加容易理解。
2424
这意味着,asyncio 不仅适合 I/O 的并发,也可以在 CPU 密集操作中使用。
2525

@@ -135,7 +135,7 @@ The current thread is MainThread
135135
这里一种 race condition 竟态条件,多线程是许多编程语言的实现并发的一种方式,但由于 GIL 的限制,python 的多线程只对 I/O-bound 类型有效。
136136

137137
此外,还可以使用多进程,即 multiprocessing,一个父进程会创建子进程并管理这些进程,然后将工作内存分发给这些子进程。
138-
multiprocessing 的 API 类似 multithreading,首先创建一个 target function,然后调用 start 方法执行,最后 join 等待运行完成。
138+
multiprocessing 的 API 类似 threading,首先创建一个 target function,然后调用 start 方法执行,最后 join 等待运行完成。
139139

140140
```Python
141141
import os

content/posts/2025-11-20_python-asyncio-02.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ tags = ['Python', 'Asyncio']
77

88
### Introducing coroutines
99

10-
创建一个协程 coroutine 和创建一个函数很类型,使用 `async def` 关键字,而不是 `def`:
10+
创建一个协程 coroutine 而不是创建一个函数类型,使用 `async def` 关键字,而不是 `def`:
1111

1212
```Python
1313
async def coroutine_add_one(number: int) -> int:
@@ -160,7 +160,7 @@ async def main():
160160
asyncio.run(main())
161161
```
162162

163-
`asyncio.create_task()` 会启动协程并立即让事件循环调度它,这里的 `await` 做的只是等待 task 完成,在等待其间,事件循环仍然会继续运行。
163+
`asyncio.create_task()` 会启动协程并立即让事件循环调度它,这里的 `await` 做的只是等待 task 完成,在等待期间,事件循环仍然会继续运行。
164164
上面代码一共会消耗 3 秒的时间,如果启动 10 个任务,也只会消耗 3 秒多时间,这就比顺序执行快了 n 倍!
165165

166166
并且不止于此,在等待的时间里,还可以执行其他代码,例如下面每秒输出状态消息:

0 commit comments

Comments
 (0)