【问题标题】:How to use pool of threads in python, in this case在这种情况下,如何在 python 中使用线程池
【发布时间】:2019-11-27 13:07:40
【问题描述】:

假设我想在文件的每一行中处理彼此不依赖的字符串。我通常是怎么做的:

def process_line(filelines, i):
    #process lines
import threading
threads = []
lines = open(file).readlines()
for i in range(0,len(lines)):
    threads.append(threading.Thread(target=process_line, args=(lines,i,))

[t.start() for t in threads]
[t.join() for t in threads]

【问题讨论】:

    标签: python multithreading pool


    【解决方案1】:
    from concurrent.futures import ThreadPoolExecutor
    
    with ThreadPoolExecutor() as executor:
        [executor.submit(proccess_line, lines, i) for i in range(len(lines))]
    

    ThreadPoolExecutor 文档:https://docs.python.org/3/library/concurrent.futures.html

    请注意,这些类型的任务最好使用进程而不是线程(将 ThreadPoolExecutor 替换为 ProccessPoolExecutor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2022-01-23
      • 2015-11-30
      • 2017-05-16
      • 2012-10-06
      • 2011-05-18
      相关资源
      最近更新 更多