在Ubuntu环境下,Python可以通过多种方式实现并发。以下是一些常用的方法:
threading模块允许你创建和管理线程。由于GIL(全局解释器锁)的存在,CPython解释器在同一时刻只能执行一个线程的字节码,这意味着多线程在处理I/O密集型任务时可以提高效率,但对于CPU密集型任务,多线程并不能提高性能。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')
if __name__ == '__main__':
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')
async def main():
tasks = []
for i in range(5):
task = asyncio.create_task(worker())
tasks.append(task)
await asyncio.gather(*tasks)
asyncio.run(main())
asyncio库就是基于协程的。import asyncio
async def coroutine_example():
print("Coroutine started")
await asyncio.sleep(1)
print("Coroutine ended")
async def main():
await coroutine_example()
asyncio.run(main())
gevent和eventlet,它们通过使用轻量级的线程(称为greenlet)来提供并发。选择哪种并发模型取决于你的具体需求,例如任务的性质(I/O密集型还是CPU密集型)、性能要求、代码复杂性等因素。