在CentOS系統下,Python腳本可以通過多種方式實現并發處理。以下是幾種常見的方法:
threading
模塊threading
模塊允許你創建和管理線程。
import threading
def worker(num):
"""線程執行的任務"""
print(f"Worker: {num}")
threads = []
for i in range(5):
thread = threading.Thread(target=worker, args=(i,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
multiprocessing
模塊multiprocessing
模塊允許你創建和管理進程,適用于CPU密集型任務。
import multiprocessing
def worker(num):
"""進程執行的任務"""
print(f"Worker: {num}")
if __name__ == "__main__":
processes = []
for i in range(5):
process = multiprocessing.Process(target=worker, args=(i,))
processes.append(process)
process.start()
for process in processes:
process.join()
concurrent.futures
模塊concurrent.futures
模塊提供了一個高級接口來執行異步任務。
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def worker(num):
"""任務函數"""
print(f"Worker: {num}")
# 使用線程池
with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(worker, i)
# 使用進程池
with ProcessPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(worker, i)
asyncio
模塊asyncio
模塊適用于I/O密集型任務,通過協程實現并發。
import asyncio
async def worker(num):
"""協程任務"""
print(f"Worker: {num}")
await asyncio.sleep(1)
async def main():
tasks = [worker(i) for i in range(5)]
await asyncio.gather(*tasks)
asyncio.run(main())
gevent
庫gevent
是一個基于協程的Python網絡庫,通過monkey patching實現并發。
首先,安裝gevent
:
pip install gevent
然后,編寫腳本:
from gevent import monkey; monkey.patch_all()
import gevent
def worker(num):
"""協程任務"""
print(f"Worker: {num}")
gevent.sleep(1)
jobs = [gevent.spawn(worker, i) for i in range(5)]
gevent.joinall(jobs)
選擇哪種方法取決于你的具體需求:
threading
適用于I/O密集型任務。multiprocessing
適用于CPU密集型任務。concurrent.futures
提供了一個高級接口,簡化了并發編程。asyncio
適用于I/O密集型任務,特別是網絡編程。gevent
適用于需要高性能的網絡應用。根據你的任務類型和性能需求,選擇最合適的方法來實現并發處理。