01. threading 多线程
threading 模块提供多线程支持。由于 Python 的 GIL,多线程适合 I/O 密集型任务,不适合 CPU 密集型任务。
python
import threading
import time
def download(url):
print(f"开始下载 {url}")
time.sleep(2)
print(f"完成下载 {url}")
# 多线程执行
threads = []
for url in ["url1", "url2", "url3"]:
t = threading.Thread(target=download, args=(url,))
threads.append(t)
t.start()
for t in threads:
t.join()
# 使用 ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=3) as executor:
executor.map(download, urls)02. asyncio 异步编程
asyncio 是 Python 的异步编程框架,使用 async/await 语法。适合高并发 I/O 操作,如网络请求、文件操作等。
python
import asyncio
async def greet(name):
await asyncio.sleep(1)
return f"Hello, {name}!"
async def main():
# 并发执行
results = await asyncio.gather(
greet("Alice"),
greet("Bob"),
greet("Charlie"),
)
print(results)
asyncio.run(main())知识测验
第 1/5 题正确 0
Python 的 GIL 对多线程有什么影响?
下一节
下一节 自动化脚本