在Ubuntu上使用Python进行并发编程,你可以使用多种方法。以下是一些常见的并发编程模型和如何在Python中实现它们的示例:
threading
模块允许你创建和管理线程。import threading
def worker():
"""线程要执行的函数"""
print('Worker')
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
for t in threads:
t.join()
multiprocessing
模块允许你创建和管理进程,这对于CPU密集型任务特别有用,因为它可以利用多个CPU核心。from multiprocessing import Process
def worker():
"""进程要执行的函数"""
print('Worker')
if __name__ == '__main__':
processes = []
for i in range(5):
p = Process(target=worker)
processes.append(p)
p.start()
for p in processes:
p.join()
asyncio
模块提供了一个事件循环来编写并发代码,使用async
/await
语法。import asyncio
async def worker():
"""异步函数"""
print('Worker')
await asyncio.sleep(1)
async def main():
tasks = []
for i in range(5):
tasks.append(asyncio.create_task(worker()))
await asyncio.gather(*tasks)
asyncio.run(main())
import gevent
def worker():
"""协程函数"""
print('Worker')
gevent.sleep(1)
jobs = [gevent.spawn(worker) for i in range(5)]
gevent.joinall(jobs)
concurrent.futures
模块提供了高级接口来使用线程池和进程池。from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def worker():
"""函数"""
print('Worker')
# 使用线程池
with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(worker)
# 使用进程池
with ProcessPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(worker)
在选择并发模型时,需要考虑任务的性质(I/O密集型还是CPU密集型)、性能要求以及Python的全局解释器锁(GIL)对多线程的影响。对于I/O密集型任务,多线程或异步IO通常是更好的选择;而对于CPU密集型任务,多进程可能更合适。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>