【问题标题】:Simplest way to do multi-threading/parallel processing in Python [duplicate]在 Python 中进行多线程/并行处理的最简单方法 [重复]
【发布时间】:2017-01-31 06:53:05
【问题描述】:

我有一个文件列表,需要在拼接在一起之前只使用一个命令进行预处理。此预处理命令通过系统调用使用第三方软件来写入 geoTIFF。我想使用多线程,以便可以同时对单个文件进行预处理,然后在处理完所有单个文件后,将结果拼接在一起。

我之前从未使用过多线程/并行处理,在互联网上搜索了数小时后,我仍然不知道最好、最简单的方法是什么。

基本上是这样的:

files_list = # list of .tif files that need to be mosaicked together but first, need to be individually pre-processed

for tif_file in files_list:
    # kick the pre-processing step out to the system, but don't wait for it to finish before moving to preprocess the next tif_file

# wait for all tiffs in files_list to finish pre-processing
# then mosaick together

我怎样才能做到这一点?

【问题讨论】:

  • 预处理的输出是什么?
  • 这个任务应该并行化有什么理由吗?由于 python 对多线程的开销,一个接一个地处理这些文件肯定会快得多(除了少数特殊情况)。
  • @PeterWood 预处理步骤的输出是我需要拼接在一起的 geoTIFFs
  • geoTIFF 是文件还是在内存中?
  • @TomaszPlaskota 好吧,目的是让代码更快,哈哈。你能更详细地解释一下吗?你怎么知道是这样的?谢谢

标签: python linux multithreading


【解决方案1】:

请参阅multiprocessing 文档。

from multiprocessing import Pool

def main():
    pool = Pool(processes=8)
    pool.map(pre_processing_command, files_list)

    mosaic()

if __name__ == '__main__':
    main()

【讨论】:

    【解决方案2】:

    如果你需要使用多个处理器内核,你应该使用multiprocess,在最简单的情况下你可以使用类似的东西:

    def process_function(tif_file):
        ... your processing code here ...
    
    for tif_file in files_list:
        p = Process(target=process_function, args=(tif_file))
        p.start()
        p.join()
    

    你需要小心,因为同时运行的进程太多会超出PC资源,你可以看看herehere解决问题。

    您也可以使用threading.thread,但它只使用一个处理器内核,并受Global Interpreter Lock的限制

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多