在Ubuntu下,Python可以通过多种方式实现并发。以下是一些常用的方法:
threading
模块允许你创建和管理线程。由于GIL(全局解释器锁)的存在,CPython解释器在同一时刻只能执行一个线程的字节码,这意味着多线程并不适合CPU密集型任务。但对于I/O密集型任务,如文件读写、网络请求等,多线程仍然是有用的。import threading def worker(): """线程执行的任务""" print('Worker') threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() for t in threads: t.join()
multiprocessing
模块可以创建多个进程,每个进程都有自己的Python解释器和内存空间,因此可以绕过GIL的限制,适合CPU密集型任务。from multiprocessing import Process def worker(): """进程执行的任务""" print('Worker') processes = [] for i in range(5): p = Process(target=worker) processes.append(p) p.start() for p in processes: p.join()
asyncio
模块提供了一种基于事件循环的并发模型,适用于I/O密集型任务。通过使用async
和await
关键字,你可以编写出看起来像同步代码的异步代码。import asyncio async def worker(): """异步任务""" print('Worker') await asyncio.sleep(1) async def main(): tasks = [worker() for _ in range(5)] await asyncio.gather(*tasks) asyncio.run(main())
asyncio
一起使用。import asyncio async def coroutine_example(): print("Coroutine started") await asyncio.sleep(1) print("Coroutine finished") async def main(): await coroutine_example() asyncio.run(main())
gevent
和eventlet
,它们通过使用轻量级的线程(称为greenlet)来实现并发。选择哪种并发模型取决于你的具体需求和任务的性质。对于I/O密集型任务,多线程、异步编程和协程通常是较好的选择。而对于CPU密集型任务,多进程可能是更好的选择。