Python,高效实现多线程IO

问题描述 投票:0回答:1

目前,我有一些密集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的新手,任何建议都会有所帮助。

python multithreading subprocess
1个回答
0
投票

好吧,我假设你的进程是链接的,因此无法异步运行。

我建议管道进程而不是使用wait。像下面的东西

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)

休息看起来不错。

© www.soinside.com 2019 - 2024. All rights reserved.