在Ubuntu上使用Python实现并发处理有多种方法,以下是一些常用的方法:
Python的threading
模块允许你创建和管理线程。
import threading def worker(): """线程要执行的函数""" print(f"线程 {threading.current_thread().name} 正在运行") threads = [] for i in range(5): thread = threading.Thread(target=worker) threads.append(thread) thread.start() for thread in threads: thread.join()
Python的multiprocessing
模块允许你创建和管理进程,每个进程都有自己的Python解释器实例。
import multiprocessing def worker(): """进程要执行的函数""" print(f"进程 {multiprocessing.current_process().name} 正在运行") processes = [] for i in range(5): process = multiprocessing.Process(target=worker) processes.append(process) process.start() for process in processes: process.join()
Python的asyncio
模块提供了一种基于协程的并发编程方式,适用于I/O密集型任务。
import asyncio async def worker(): """协程函数""" print("协程正在运行") await asyncio.sleep(1) print("协程结束") async def main(): tasks = [worker() for _ in range(5)] await asyncio.gather(*tasks) asyncio.run(main())
还有一些第三方库可以帮助你实现并发处理,例如concurrent.futures
。
from concurrent.futures import ThreadPoolExecutor def worker(): """线程要执行的函数""" print(f"线程 {threading.current_thread().name} 正在运行") with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(worker) for _ in range(5)] for future in futures: future.result()
from concurrent.futures import ProcessPoolExecutor def worker(): """进程要执行的函数""" print(f"进程 {multiprocessing.current_process().name} 正在运行") with ProcessPoolExecutor(max_workers=5) as executor: futures = [executor.submit(worker) for _ in range(5)] for future in futures: future.result()
concurrent.futures
提供了更高级的并发处理接口,简化了代码编写。根据你的具体需求选择合适的方法来实现并发处理。