python - Python中的多处理,每个进程处理一个文件的一部分

标签 python multithreading parallel-processing

我有一个文件想用 Python 处理。 此文件中的每一行都是图像的路径,我想对每个图像调用特征提取算法。

我想将文件分成更小的 block ,每个 block 将在一个并行的单独进程中处理。 对于 Python 中的这种多处理,有哪些最先进的库或解决方案?

最佳答案

您的描述表明一个简单的线程(或进程)池可以工作:

#!/usr/bin/env python
from multiprocessing.dummy import Pool # thread pool
from tqdm import tqdm # $ pip install tqdm # simple progress report

def mp_process_image(filename):
    try:
       return filename, process_image(filename), None
    except Exception as e:
       return filename, None, str(e)

def main():
    # consider every non-blank line in the input file to be an image path
    image_paths = (line.strip()
                   for line in open('image_paths.txt') if line.strip())
    pool = Pool() # number of threads equal to number of CPUs
    it = pool.imap_unordered(mp_process_image, image_paths, chunksize=100)
    for filename, result, error in tqdm(it):
        if error is not None:
           print(filename, error)

if __name__=="__main__":
    main() 

我假设 process_image() 受 CPU 限制,它会释放 GIL,即它在 OpenCV 等 C 扩展中完成主要工作。如果 process_image() 不释放 GIL,则从 Pool 导入中删除单词 .dummy 以使用进程而不是线程。

关于python - Python中的多处理,每个进程处理一个文件的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637273/

相关文章:

multithreading - 强制MPI使用指定的编号。核心

c - 使用 CUDA 内核获取堆栈溢出

python - 如何从元组中随机选择一个字符串并随机插入文本中的每一行?

python - 在Spark中,RDD是不可变的,那么Accumulators是如何实现的呢?

python - Keras 模型的自定义指标,使用 Tensorflow 2.1

java - 多线程文件传输到 FTP 服务器

c# - C# 是否具有 "ThreadLocal"属性的 "ThreadStatic"模拟(对于数据成员)?

python - 在 HTTP POST header 中包含 session

android - 当另一个可观察量完成时订阅另一个可观察量

java - java程序在多核机器上如何提高性能