ubuntu

Ubuntu中Python的并发如何实现

小樊
45
2025-09-06 18:50:15
栏目: 编程语言

在Ubuntu中,Python的并发可以通过多种方式实现,包括多线程、多进程和异步编程。以下是每种方法的简要说明和示例:

1. 多线程(Threading)

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.")

2. 多进程(Multiprocessing)

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.")

3. 异步编程(Asyncio)

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())

4. 使用第三方库

还有一些第三方库可以帮助实现并发,例如concurrent.futuresgevent

使用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密集型任务,多进程则更为合适。

0
看了该问题的人还看了