在Ubuntu中,Python的并發可以通過多種方式實現,包括多線程、多進程和異步編程。以下是每種方法的簡要說明和示例:
Python的多線程適用于I/O密集型任務,因為GIL(全局解釋器鎖)限制了同一時間只能有一個線程執行Python字節碼。
import threading
def worker():
"""線程執行的任務"""
print(f"Thread {threading.current_thread().name} is running")
threads = []
for i in range(5):
thread = threading.Thread(target=worker)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print("All threads have finished.")
Python的多進程適用于CPU密集型任務,因為每個進程都有自己的Python解釋器實例,不受GIL的限制。
import multiprocessing
def worker():
"""進程執行的任務"""
print(f"Process {multiprocessing.current_process().name} is running")
processes = []
for i in range(5):
process = multiprocessing.Process(target=worker)
processes.append(process)
process.start()
for process in processes:
process.join()
print("All processes have finished.")
Python的異步編程適用于I/O密集型任務,通過事件循環和協程實現高效的并發。
import asyncio
async def worker():
"""異步任務"""
print("Worker is running")
await asyncio.sleep(1)
print("Worker has finished")
async def main():
tasks = [worker() for _ in range(5)]
await asyncio.gather(*tasks)
asyncio.run(main())
還有一些第三方庫可以幫助實現并發,例如concurrent.futures
和gevent
。
concurrent.futures
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def worker():
"""任務函數"""
print(f"Worker is running")
# 使用線程池
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(worker) for _ in range(5)]
for future in futures:
future.result()
# 使用進程池
with ProcessPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(worker) for _ in range(5)]
for future in futures:
future.result()
gevent
import gevent
from gevent import monkey
monkey.patch_all()
def worker():
"""任務函數"""
print(f"Worker {gevent.getcurrent()} is running")
gevent.sleep(1)
print(f"Worker {gevent.getcurrent()} has finished")
jobs = [gevent.spawn(worker) for _ in range(5)]
gevent.joinall(jobs)
選擇哪種方法取決于你的具體需求和任務的性質。對于I/O密集型任務,多線程和異步編程通常是更好的選擇;而對于CPU密集型任務,多進程則更為合適。