在Python中并行处理不同参数的函数

Process a function on different arguments in parallel in Python

这是我要并行运行printrange()的简单代码:

1
2
3
4
5
6
7
def printRange(lrange):
    print ("First is" + str(lrange[0]) +" and last is" + str(lrange[1]))


def runInParallel():
    ranges = [[0, 10], [10, 20], [20, 30]]
    // Call printRange in parallel with each sublist of ranges given as argument

我的问题不同于这个问题,所以在这里,每个过程都是硬编码的,开始的,最后加入的。我想将printrange()与其他100个printrange()工作函数并行运行。每次硬编码都是不可行的。怎么能做到?


使用多处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from multiprocessing import Pool


def print_range(lrange):
    print('First is {} and last is {}'.format(lrange[0], lrange[1]))


def run_in_parallel():
    ranges = [[0, 10], [10, 20], [20, 30]]
    pool = Pool(processes=len(ranges))
    pool.map(print_range, ranges)


if __name__ == '__main__':
    run_in_parallel()

输出:

1
2
3
First is 0 and last is 10
First is 10 and last is 20
First is 20 and last is 30

像这样?

1
2
3
4
5
6
7
8
9
10
11
12
import threading

def printRange(lrange):
    print ("First is" + str(lrange[0]) +" and last is" + str(lrange[1]))

def runInParallel():
    ranges = [[0, 10], [10, 20], [20, 30]]
    for i in ranges:
        t = threading.Thread(target=printRange, args = [i])
        t.start()

runInParallel()