python实现并发
python封装了4种常用方法,map, apply, map_async, apply_async用于实现并发。注意:map 和 map_async 入参为迭代器类型,可以批量调用。而apply和apply_async只能一个个调用。
多参数 | 并发 | 上锁 | 结果有序 | |
---|---|---|---|---|
map | × | √ | √ | √ |
apply | √ | × | √ | × |
map_async | × | √ | × | √ |
apply_async | √ | √ | × | × |
map
使用map指定迭代器传参,并发线程算平方。
import concurrent.futures
def process_item(item):
result = item ** 2 # 处理结果
return result
def concurrent_map(func, items):
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(func, items)#指定处理函数,和迭代器传入参数
return list(results)
# 使用示例
data = [1, 2, 3, 4, 5]
results = concurrent_map(process_item, data)
print(results)
map_async
map_async 是 multiprocessing.Pool 类提供的一个方法,用于并发地执行函数映射,这里使用进程池。
from multiprocessing import Pool
def square(x):
return x ** 2
if __name__ == '__main__':
# 创建进程池
pool = Pool()
# 调用 map_async 方法执行函数映射
result = pool.map_async(square, range(10))
# 等待所有任务完成并获取结果
output = result.get()
# 打印结果
print(output)
对比1:map和map_async
1,阻塞:map 方法是阻塞的,而 map_async 方法是非阻塞的。当调用 map 方法时,程序会阻塞在该语句,直到所有任务完成并返回结果。相比之下,map_async 方法会立即返回一个结果对象,不会阻塞。
2,返回值:map 方法会直接返回函数映射的结果列表,而 map_async 方法返回一个结果对象。使用该对象的 get() 方法获取最终的结果列表。
3,异常处理:map 方法会立即抛出任何引发的异常,而 map_async 方法不会立即抛出异常,而是将其记录在结果对象中。可以使用结果对象的 get() 方法来获取结果并处理任何可能的异常。
apply
apply 方法已经在 Python 3.3 中被废弃,并在 Python 3.8 中移除。官方推荐使用更高级的接口apply_async
apply_async
它可以在进程池中异步地执行函数,并返回一个结果对象,该对象可以用于获取函数的返回值。
from multiprocessing import Pool
def square(x):
return x ** 2
if __name__ == '__main__':
# 创建进程池
pool = Pool()
# 创建任务列表
tasks = [2, 3, 4]
# 使用 apply_async 方法并发执行任务
results = [pool.apply_async(square, (task,)) for task in tasks]
# 获取并打印结果(无序)
for result in results:
output = result.get()
print(output)
apply_anysc的结果是无序的,但这里的任务太小了,会造成有序的场面。