多线程(Threading)
使用`threading`模块创建和管理线程。
适合I/O密集型任务,如文件读写、网络请求等。
注意:由于Python的全局解释器锁(GIL),多线程在CPU密集型任务上不会有性能提升。
多进程(Multiprocessing)
使用`multiprocessing`模块创建和管理进程。
适合CPU密集型任务,因为每个进程都有自己独立的Python解释器,不受GIL的限制。
可以使用`concurrent.futures.ProcessPoolExecutor`来简化多进程的创建和管理。
异步编程(Asyncio)
使用`asyncio`模块实现异步编程,适合高并发的I/O操作。
第三方库
`gevent`等第三方库提供了更高级的并发处理方式。
`joblib`库除了并行计算,还实现了缓存和序列化功能。
示例代码
多线程示例

import threadingimport timedef worker(name):for i in range(5):print(f"{name} is working: {i}")time.sleep(1)threads = []for i in range(3):thread = threading.Thread(target=worker, args=(f"Thread-{i+1}",))threads.append(thread)thread.start()for thread in threads:thread.join()print("所有线程都完成了工作")
多进程示例
from multiprocessing import Processdef worker():print("This is a process running the worker function.")processes = []for _ in range(5):p = Process(target=worker)processes.append(p)p.start()for p in processes:p.join()
异步编程示例
import asyncioasync def worker(name):for i in range(5):print(f"{name} is working: {i}")await asyncio.sleep(1)async def main():tasks = [worker(f"Task-{i+1}") for i in range(3)]await asyncio.gather(*tasks)asyncio.run(main())
选择哪种并发方式取决于你的具体需求,包括任务的性质(I/O密集型或CPU密集型)以及你对性能和资源使用的考虑。希望这些示例能帮助你理解如何在Python中实现并发
