在Ubuntu中,Python可以通过多种方式实现并发编程。以下是一些常用的方法:
Python的threading
模块允许你创建和管理线程。
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()
Python的multiprocessing
模块允许你创建和管理进程,每个进程都有自己的Python解释器实例,因此可以避免GIL(全局解释器锁)的限制。
from multiprocessing import Process
def worker():
"""进程执行的任务"""
print(f"Process {multiprocessing.current_process().name} is running")
processes = []
for i in range(5):
process = Process(target=worker)
processes.append(process)
process.start()
for process in processes:
process.join()
Python的asyncio
模块提供了一种基于事件循环的并发编程模型,适用于I/O密集型任务。
import asyncio
async def worker():
"""异步任务"""
print("Worker is running")
await asyncio.sleep(1)
print("Worker is done")
async def main():
tasks = [worker() for _ in range(5)]
await asyncio.gather(*tasks)
asyncio.run(main())
协程是一种特殊的函数,可以在执行过程中暂停并在稍后恢复。Python的asyncio
库提供了对协程的支持。
import asyncio
async def coroutine_example():
print("Coroutine started")
await asyncio.sleep(1)
print("Coroutine ended")
asyncio.run(coroutine_example())
还有一些第三方库可以帮助实现并发编程,例如:
from gevent import monkey; monkey.patch_all()
import gevent
def worker():
"""协程任务"""
print(f"Worker {gevent.getcurrent()} is running")
gevent.sleep(1)
print(f"Worker {gevent.getcurrent()} is done")
jobs = [gevent.spawn(worker) for _ in range(5)]
gevent.joinall(jobs)
from concurrent.futures import ThreadPoolExecutor
def worker():
"""线程任务"""
print(f"Thread {threading.current_thread().name} is running")
return "Done"
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(worker) for _ in range(5)]
for future in concurrent.futures.as_completed(futures):
print(future.result())
选择哪种方法取决于你的具体需求和应用场景。对于I/O密集型任务,asyncio
和gevent
通常是更好的选择;而对于CPU密集型任务,multiprocessing
可能更合适。