Python多处理——跟踪pool.map操作的过程

在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个元素的列表,并使用进程池对这个列表进行映射。当我们运行这个程序时,我们应该看到每个任务都被正确地分配给一个工作进程,并且我们在控制台上可以看到每一步的进度。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值