如何在 Python 中并行处理列表?

How to process a list in parallel in Python?

我写的代码是这样的:

def process(data):
   #create file using data

all = ["data1", "data2", "data3"]

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

如何使用 python 2.7 中的默认模块执行此操作?

有使用模板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()

这里假设 CPython 和 GIL

如果您的任务受 I/O 限制,一般来说,线程可能更高效,因为线程只是将工作转储到操作系统上并空闲,直到 I/O 操作完成。产卵过程是照顾婴儿的繁重方式 I/O。

但是,大多数文件系统不是并发的,因此使用多线程或多处理可能不会比同步写入快。

尽管如此,这里有一个 multiprocessing.Pool.map 的人为示例,它可能有助于您的 CPU-绑定工作:

from multiprocessing import cpu_count, Pool

def process(data):
    # best to do heavy CPU-bound work here...

    # file write for demonstration
    with open("%s.txt" % data, "w") as f:
        f.write(data)

    # example of returning a result to the map
    return data.upper()
      
tasks = ["data1", "data2", "data3"]
pool = Pool(cpu_count() - 1)
print(pool.map(process, tasks))

可以在 concurrent.futures.ThreadPoolExecutor 中找到类似的线程设置。

顺便说一句,all 是一个内置函数,并不是一个很好的变量名选择。

或者:

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()

或者(仅 python 版本 > 3.6.0):

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()