溫馨提示×

CentOS下Python腳本如何實現并發處理

小樊
36
2025-08-25 00:38:04
欄目: 編程語言

在CentOS系統下,Python腳本可以通過多種方式實現并發處理。以下是幾種常見的方法:

1. 使用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()

2. 使用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()

3. 使用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)

4. 使用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())

5. 使用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適用于需要高性能的網絡應用。

根據你的任務類型和性能需求,選擇最合適的方法來實現并發處理。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女