【问题标题】:Python : How to create n processes and iterate over a listPython:如何创建 n 个进程并遍历列表
【发布时间】:2015-08-04 13:36:45
【问题描述】:

我有一个如下所述的数字列表(元素):

Elements = [['1','5'], ['2','5'], ['3','5'], ['4','5'], ['5', '5'], ['6', '5'], ['7', '5'], ['8', '5'], ['9', '5'], ['10', '5']]

我想调用函数main(x1,y1),使用x1=records[0]y1=records[1] 中的记录来获取Elements 中的记录。 我想打电话给main(),说有10个进程同时处理来自Elements的前10条记录。完成后,从 Elements 调用接下来的 10 条记录并执行相同的操作并重复,直到所有记录都由 main() 处理。我是 python 新手,所以如果有人能帮助我,那就太好了。

这是我的代码-

def main(x1,y1):
  do something
  do something

import multiprocessing as mp
output = mp.Queue()

processes = [mp.Process(target=main, args=(records[0], records[1], output)) for records in Elements]

# Run processes
for p in processes:
    p.start()

# Exit the completed processes
for p in processes:
    p.join()

# Get process results from the output queue
results = [output.get() for p in processes]

print(results)

【问题讨论】:

  • 理论上,如果每个元素需要进行大量处理,列表的多处理元素可能会运行得更快,但问题是据我所知,Python 列表没有实现并发访问 -如果这样做,它会被大量宣传。因此,首先将列表拆分为较小的单独列表并同时处理它们会很有用。线程池执行器类使并发处理变得容易,参见docs.python.org/3/library/concurrent.futures.html

标签: python multithreading process


【解决方案1】:

你可以用Pool做这样的事情:

from multiprocessing import Pool

PROCESS_COUNT = 10

elements = [['1','5'], ['2','5'], ['3','5'], ['4','5'], ['5', '5'], ['6', '5'], ['7', '5'], ['8', '5'], ['9', '5'], ['10', '5']]

def main(element):
    # let's say you want to have concatenations as the results
    return element[0] + element[1]

pool = Pool(PROCESS_COUNT)
results = pool.map(main, elements)
pool.close()
pool.join()
# now results is a list of concatenations: ['15', '25', '35', '45', '55', '65', '75', '85', '95', '105']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2019-01-28
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    相关资源
    最近更新 更多