使用池进程保留主阵列

时间:2018-12-18 14:21:48

标签: python python-multiprocessing pool

我刚刚开始学习如何在python中使用Pool进程,并且对返回全局数组有疑问。例如,我有以下代码片段:

import time
import numpy as np
import random
import multiprocessing
from multiprocessing import Pool

def f2(list):
    # append squares of mylist to result array
    out = []
    for idx, num in enumerate(list):
        out.append(idx)
    return out

def f_amp(a_list, list2, num_cores):
    chunks = [list2[i::num_cores] for i in range(num_cores)]
    out = np.array(len(list2))
    pool = Pool(processes=num_cores)

    # data = [chunks, out]
    result = pool.map_async(f2,chunks)

    while not result.ready():
        print("Running...")
        time.sleep(0.5)

    return result.get(0)

if __name__ == "__main__":
    num_cores = multiprocessing.cpu_count();
    print("Number of cores: ", num_cores)
    N = 10
    a_list = np.linspace(1, N, N)
    list2 = random.sample(range(1, N+1), N)
    print(list2)
    start = time.time()
    result = f_amp(a_list, list2, num_cores)
    end = time.time()
    print(end - start)
    print(result)

运行此命令,结果为[[0,1,2],[0,1,2],[0,1],[0,1]]。所以我的问题是如何使返回的结果类似于

[[0,0,0,0,1,1,1,1,2,2]]

0 个答案:

没有答案