在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密集型任務,多進程可能是更好的選擇。