在Python中,`multiprocessing.Pool.map()`函数用于并行地执行一个函数在一个列表的每个元素上。但是,这并不能让我们清楚地知道每次执行的任务是哪一个。如果我们想在使用`pool.map()`时追踪`pool.map`操作的过程,我们可以通过自定义装饰器来实现。
以下是一个简单的例子:
```python
import multiprocessing as mp
def track_progress(func):
"""Decorator to track the progress of a pool.map function."""
def wrapper(pool, iterable, *args, **kwargs):
# Create a queue to store the results and a list to keep track of completed tasks
results = []
completed = 0
# Define an inner function that will be used by the pool
def worker(item, index):
nonlocal results, completed
result = func(pool, item, *args, **kwargs)
results.insert(index, result)
completed += 1
print(f"Task {index + 1}/{len(iterable)} completed: {item}")
# Create a pool of workers and apply the wrapper function to each element in iterable
with mp.Pool() as p:
p.starmap(worker, enumerate(iterable), chunksize=1)
return results
return wrapper
@track_progress
def example_func(pool, item, *args, **kwargs):
"""Example function to be mapped."""
print(f"Processing {item}")
# Simulate some processing time
import random
time = random.randint(1, 5)
print(f"{item} processed in {time} seconds.")
return item * len(args)
if __name__ == "__main__":
iterable = [i for i in range(10)]
with mp.Pool() as p:
results = example_func(p, iterable)
print("All tasks completed.")
print(f"Results: {results}")
```
在这个例子中,我们定义了一个名为`track_progress`的装饰器,它接受一个函数作为参数。这个装饰器返回一个新的函数,这个新函数会创建一个进程池,并在每个任务完成后打印出任务的进度。
然后我们定义了一个名为`example_func`的函数,这个函数模拟了一个处理任务的时间。我们在`@track_progress`装饰器后使用`example_func`来装饰它,这样我们就可以在`pool.map()`操作的过程中追踪任务。
在主程序中,我们创建了一个包含10个元素的列表,并使用进程池对这个列表进行映射。当我们运行这个程序时,我们应该看到每个任务都被正确地分配给一个工作进程,并且我们在控制台上可以看到每一步的进度。