欢迎访问宙启技术站
智能推送

Python中的并发编程模式:多任务协作与资源共享

发布时间:2024-01-04 15:15:11

Python中的并发编程模式主要有多任务协作与资源共享两种。多任务协作是指多个任务在同一时间段内共享计算机的CPU资源,通过协作调度实现同时执行的效果。资源共享则是多个任务共享同一份数据,通过加锁机制实现对共享资源的互斥访问。

在Python中,可以使用多线程、多进程、异步编程等方式来实现并发编程。

1. 多线程:

多线程是在单个进程内创建多个线程来执行任务,由于GIL(全局解释器锁)的存在,Python的多线程并不能真正实现多核并行。但是对于IO密集型任务,多线程可以实现并发执行。

例如,下面的代码使用多线程同时下载多个网页的内容:

import requests
import threading

def download(url):
    res = requests.get(url)
    print(res.text)

urls = ['http://example.com', 'http://example.org', 'http://example.net']

threads = []
for url in urls:
    t = threading.Thread(target=download, args=(url,))
    t.start()
    threads.append(t)

for thread in threads:
    thread.join()

2. 多进程:

多进程是在操作系统中创建多个进程来执行任务,每个进程都有自己独立的内存空间和CPU资源,可以实现真正的多核并行。

例如,下面的代码使用多进程同时计算多个数的平方:

import multiprocessing

def square(x):
    return x**2

numbers = [1, 2, 3, 4, 5]

with multiprocessing.Pool(processes=4) as pool:
    results = pool.map(square, numbers)

print(results)

3. 异步编程:

异步编程是通过事件循环机制实现任务的并发执行,避免了线程或进程的切换开销,适用于IO密集型任务。

示例代码如下:

import asyncio

async def download(url):
    res = await aiohttp.get(url)
    print(res.text)

urls = ['http://example.com', 'http://example.org', 'http://example.net']

event_loop = asyncio.get_event_loop()
tasks = [download(url) for url in urls]
event_loop.run_until_complete(asyncio.wait(tasks))
event_loop.close()

总结:

Python中的并发编程模式有多任务协作与资源共享两种。多线程适用于IO密集型任务,多进程适用于计算密集型任务,而异步编程适用于IO密集型任务并希望充分利用CPU资源的场景。通过合理选择并发编程模式,可以充分利用计算机的性能,提高程序的运行效率。