首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,多线程IO的高效实现

Python,多线程IO的高效实现
EN

Stack Overflow用户
提问于 2017-12-27 01:47:49
回答 1查看 90关注 0票数 0

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

代码语言:javascript
复制
   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使用三个线程队列来避免等待()或文件读取。

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

EN

回答 1

Stack Overflow用户

发布于 2017-12-27 02:46:12

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

我建议通过管道传输进程,而不是使用等待。类似于下面的内容

代码语言:javascript
复制
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)

休息看起来不错。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47981982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档