📚 核心概念
GIL(全局解释器锁)
- 确保同一时间只有一个线程执行Python字节码
- 保护Python内部数据结构不受并发访问影响
- 只适用于CPython解释器
协程(Coroutine)
- 轻量级并发解决方案
- 在单个线程中实现多个任务切换
- 用户空间切换,无需内核级上下文切换
线程(Thread)
进程(Process)
🎯 协程示例
import asyncio
import random
async def coroutine(id):
delay = random.randint(1, 3)
print(f"Coroutine {id} starting, will run for {delay} seconds")
await asyncio.sleep(delay)
print(f"Coroutine {id} finished")
async def main():
coroutines = []
for i in range(5):
coroutines.append(coroutine(i))
await asyncio.gather(*coroutines)
if __name__ == "__main__":
asyncio.run(main())
🧵 多线程示例
import threading
def print_numbers():
for i in range(10):
print(i)
threads = [threading.Thread(target=print_numbers) for _ in range(3)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
🖥️ 多进程示例
import multiprocessing
def print_numbers():
for i in range(10):
print(i)
processes = [multiprocessing.Process(target=print_numbers) for _ in range(3)]
for process in processes:
process.start()
for process in processes:
process.join()
⚡ 并行计算
import multiprocessing
def calculate(number):
return number ** 2
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=4)
results = pool.map(calculate, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(results)