【问题标题】:Python, Efficient implementation of multi-thread IOPython,多线程IO的高效实现
【发布时间】:2017-12-26 17:47:48
【问题描述】:

目前,我有一些密集 I/O 任务的并行实现。 例如

   def func(i):
      # Write to i.txt
      subprocess.Popen(str(i).txt).wait()   

      # Another external process to analysis i.txt and generate image i.png
      subprocess.Poen(str(i).txt).wait()    

      # read i.png
      color = open("i.png")
      return color

   pool = ThreadPool(4)
   for i in range(1000):  # Could be thousands of files
      pool.apply_async(func,i)

这两个外部进程要么是 CPU 计算密集型,要么是 GPU 密集型。

与单线程相比,它有显着的加速。 但我仍然想知道是否还有其他优化?可以使用。

IO的顺序可以优化吗?

例如,改为在一个函数中执行三个 I/O,拆分 I/O 使用三个线程队列来避免 wait() 或文件读取。

我是 python 新手,任何建议都会有所帮助。

【问题讨论】:

  • 这两个程序能输出到stdout/stdin吗?如果是这样,您始终可以将第一个子进程的输出通过管道传输到第二个子进程,然后从第二个子进程的标准输出中读取(以避免文件系统 I/O)。另外,为什么不只是pool.map(func, range(1000))
  • 一开始你必须修复你的功能,这与预期的工作相去甚远。

标签: python multithreading subprocess


【解决方案1】:

好吧,我假设您的流程是链接的,因此不能异步运行。

我建议通过管道处理进程而不是使用等待。类似下面的东西

def func(i):
    args_write = ['write', '%s.txt' % str(i)]
    args_read = ['read', '%s.txt' % str(i)]
    args_img = ['color', '%s.png' % str(i)]
    # Write to i.txt
    process_write = subprocess.Popen(args_write, stdout=subprocess.PIPE, shell=False)
    # Another external process to analysis i.txt and generate image i.png
    process_read = subprocess.Popen(args_read, stdin=process_write.stdout, stdout=subprocess.PIPE, shell=False)
    # read i.png
    process_img = subprocess.Popen(args_img, stdin=process_read.stdout, stdout=subprocess.PIPE, shell=False)

    process_write.stdout.close()
    process_read.stdout.close()
    color = process_img.communicate()[0]
    return color

pool = ThreadPool(4)
for i in range(1000):  # Could be thousands of files
    pool.apply_async(func, i)

休息看起来不错。

【讨论】:

  • 那么使用管道会不会阻塞线程?因为子进程直接写入硬盘,所以我使用 .wait() 来确保文件创建完成,以便下一个子进程能够读取创建的文件。
  • 管道不会阻塞线程,'.wait()' 可能会阻塞。 subprocess - wait docs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
相关资源
最近更新 更多