在CentOS系統下,使用Python進行并發處理有多種方法。以下是一些常用的并發處理庫和示例:
threading庫threading庫是Python內置的線程庫,可以用來實現簡單的并發處理。
import threading
def worker(num):
print(f"Worker {num}")
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
concurrent.futures庫concurrent.futures庫是Python 3.2+中的一個高級并發處理庫,提供了線程池和進程池兩種方式。
from concurrent.futures import ThreadPoolExecutor
def worker(num):
print(f"Worker {num}")
with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(worker, i)
multiprocessing庫multiprocessing庫是Python內置的多進程庫,可以用來實現多核并行處理。
import multiprocessing
def worker(num):
print(f"Worker {num}")
processes = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
processes.append(p)
p.start()
for p in processes:
p.join()
asyncio庫asyncio庫是Python 3.4+中的一個異步編程庫,可以用來實現協程并發處理。
import asyncio
async def worker(num):
print(f"Worker {num}")
async def main():
tasks = [worker(i) for i in range(5)]
await asyncio.gather(*tasks)
asyncio.run(main())
根據你的需求和場景,可以選擇合適的并發處理方法。對于I/O密集型任務,可以使用threading或asyncio;對于CPU密集型任務,可以使用multiprocessing。