代码之家  ›  专栏  ›  技术社区  ›  Joan Venge

如何在Python中并行处理列表?[副本]

  •  2
  • Joan Venge  · 技术社区  · 6 年前

    def process(data):
       #create file using data
    
    all = ["data1", "data2", "data3"]
    

    我想并行地在我的所有列表上执行process函数,因为它们正在创建小文件,所以我不担心磁盘写操作,但是处理需要很长时间,所以我想使用我的所有核心。

    如何使用Python2.7中的默认模块来实现这一点?

    3 回复  |  直到 6 年前
        1
  •  3
  •   ggorlen Hoàng Huy Khánh    6 年前

    您可以尝试以下基本示例:

    from threading import Thread
    
    def process(data):
        print "processing %s" % data
    
    all = ["data1", "data2", "data3"]
    
    for task in all:
        t = Thread(target=process, args=(task,))
        t.start()
    

    repl 还有一个 brief tutorial 它显示了如何让调用者在需要时暂停线程连接。

    关于使用所有核心,我没有任何信息,但以下是一些可能有帮助的资源:[ 1 ], [ 2 3

        2
  •  3
  •   U13-Forward    6 年前

    或:

    from threading import Thread
    
    def process(data):
        print("processing {}".format(data))
    
    l= ["data1", "data2", "data3"]
    
    for task in l:
        t = Thread(target=process, args=(task,))
        t.start()
    

    from threading import Thread
    
    def process(data):
        print(f"processing {data}")
    
    l= ["data1", "data2", "data3"]
    
    for task in l:
        t = Thread(target=process, args=(task,))
        t.start()
    
        3
  •  3
  •   pwxcoo    6 年前

    有一个使用的模板 multiprocessing

    from multiprocessing.dummy import Pool as ThreadPool
    
    def process(data):
        print("processing {}".format(data))
    alldata = ["data1", "data2", "data3"]
    
    pool = ThreadPool()
    
    results = pool.map(process, alldata)
    
    pool.close()
    pool.join()