Python多线程的高效实现I

2024-05-19 01:47:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: totxtpngdefanotherwritecolorfunc
1条回答
网友
1楼 · 发布于 2024-05-19 01:47:37

好吧,我假设您的进程是链接的,因此不能异步运行。你知道吗

我建议用管道来代替等待。像下面这样

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)

休息看起来不错。你知道吗

相关问题 更多 >

    热门问题