python 具有两个列表比较的多进程

python Multiprocess with two list compare

我在 python3.5 中有关于 multiprocess 的问题。

如果我有两个列表:

xlist = [1,2,3]
ylist = [4,5,6]

我想做:

for i in xlist:
    for j in ylist:
        print (i*j)

输出是

4
5
6
8
10
12
12
15
18

我尝试使用 Multiprocess 这样做:

import multiprocessing

global xlist
xlist = [1,2,3]
ylist = [4,5,6]

def product(ylist): 
    for x in xlist:
        for y in ylist:
            print (x,y)
    return 'OK'

if __name__ == "__main__":
    pool = multiprocessing.Pool()
    results = []
    for i in range(0, len(ylist)):
        result = pool.apply_async(job, args=(ylist,))
        results.append(result)
        # print (result.get())
    pool.close()
    pool.join()

for result in results:
    print(result.get())

但是我无法得到上面的输出显示。我的输出将是

1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
1 4
1 5
...

使用代码。

有什么方法可以达到目的(必须使用多进程)?

我认为您想先尝试一个简单的示例,然后再将其用于非常大的数字集和更复杂的函数。

这是一个程序,它可以打印您想要的内容,使用多重处理,并且应该针对更大的列表和更复杂的函数进行扩展。

import multiprocessing

xlist=[1,2,3]
ylist=[4,5,6]

def enum_tasks():
  for x in xlist:
    for y in ylist:
      yield (x,y)

def product(xy):
  x,y = xy
  return x * y

if __name__ == '__main__':
  CHUNK_SIZE = multiprocessing.cpu_count()
  pool = multiprocessing.Pool()
  for result in pool.imap(product, enum_tasks(), CHUNK_SIZE):
    print result