多处理不适用于计算矩阵的叉积的函数

时间:2017-02-15 22:41:41

标签: python python-2.7 multiprocessing python-multiprocessing

我试图比较非并行版本和函数的并行版本的运行时间。问题是,虽然并行功能适用于线程包,但是在切换到多处理包后,进程才会开始。我想知道这是否是由我的编译器或其他任何原因引起的。任何人都可以运行我的代码,看看它是否在其他环境中工作?如果没有,我的代码中的问题是什么?

import numpy as np
from multiprocessing import Process

def single_row(a,b,output):
    for j in range(len(b[0])):
        for k in range(len(a)):
            output[j]=output[j]+a[k]*b[k][j]

#Parallel Matrix Cross Multiplication
def cross_parallel(a,b):
    if len(a[0])==len(b):
        tasks=[None]*len(a)
        T=np.array([[0]*len(b[0])]*len(a))
        for i in range(len(a)):
            tasks[i]=Process(target=single_row,args=(a[i],b,T[i]))
        for task in tasks:
            task.start()
        for task in tasks:
            task.join()
        return T
    else:
        print 'Error: Invalid Matrices'

#Non-parallel Matrix Cross Multiplication
def cross_basic(a,b):
    if len(a[0])==len(b):
        T=np.array([[0]*len(b[0])]*len(a))
        for i in range(len(a)):
            for j in range(len(b[0])):
                for k in range(len(a[0])):
                    T[i][j]=T[i][j]+a[i][k]*b[k][j]
        return T
    else:
        print 'Error: Invalid Matrices'

if __name__ == '__main__':     
    x=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    y=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    print cross_basic(x,y)
    print cross_parallel(x,y)

结果:

[[ 90 100 110 120]
 [202 228 254 280]
 [314 356 398 440]
 [426 484 542 600]]
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

使用线程包的版本有效(仅在第15行有所不同):

import numpy as np
from threading import Thread

def single_row(a,b,output):
    for j in range(len(b[0])):
        for k in range(len(a)):
            output[j]=output[j]+a[k]*b[k][j]

#Parallel Matrix Cross Multiplication
def cross_parallel(a,b):
    if len(a[0])==len(b):
        tasks=[None]*len(a)
        T=np.array([[0]*len(b[0])]*len(a))
        for i in range(len(a)):
            tasks[i]=Thread(target=single_row,args=(a[i],b,T[i]))
        for task in tasks:
            task.start()
        for task in tasks:
            task.join()
        return T
    else:
        print 'Error: Invalid Matrices'

#Non-parallel Matrix Cross Multiplication
def cross_basic(a,b):
    if len(a[0])==len(b):
        T=np.array([[0]*len(b[0])]*len(a))
        for i in range(len(a)):
            for j in range(len(b[0])):
                for k in range(len(a[0])):
                    T[i][j]=T[i][j]+a[i][k]*b[k][j]
        return T
    else:
        print 'Error: Invalid Matrices'

if __name__ == '__main__':     
    x=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    y=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    print cross_basic(x,y)
    print cross_parallel(x,y)

结果:

[[ 90 100 110 120]
 [202 228 254 280]
 [314 356 398 440]
 [426 484 542 600]]
[[ 90 100 110 120]
 [202 228 254 280]
 [314 356 398 440]
 [426 484 542 600]]

1 个答案:

答案 0 :(得分:1)

当您使用线程时,结果矩阵T在线程中共享(这意味着它基本上是相同的对象,使用相同的内存槽)。因此,修改子T中的Thread将修改T的本地版本,您将获得正确的结果。

对于子流程,每个子Process都会获得T的新副本。因此,子进程中T的修改不会修改其本地版本。要获得正确的结果,您需要使用Queue发送回计算结果。但是你必须要小心,因为你得到结果的顺序不是确定性的。

import numpy as np
from multiprocessing import Process, Queue


def single_row(a, b, idx, q):
    N = len(b[0])
    output = np.zeros(N)
    for j in range(len(b[0])):
        for k in range(len(a)):
            output[j] = output[j]+a[k]*b[k][j]
    q.put((idx, output))

# Parallel Matrix Cross Multiplication


def cross_parallel(a, b):
    M = len(a)
    q = Queue()
    if len(a[0]) == len(b):
        tasks = [None]*M
        T = np.array([[0]*len(b[0])]*len(a))
        for i in range(M):
            tasks[i] = Process(target=single_row, args=(a[i], b, i, q))
        for task in tasks:
            task.start()
        T = []
        for i in range(M):
            T += [q.get()]
        for task in tasks:
            task.join()
        T.sort()
        T = np.array([v[1] for v in T])
        return T
    else:
        print('Error: Invalid Matrices')

# Non-parallel Matrix Cross Multiplication


def cross_basic(a, b):
    if len(a[0]) == len(b):
        T = np.array([[0]*len(b[0])]*len(a))
        for i in range(len(a)):
            for j in range(len(b[0])):
                for k in range(len(a[0])):
                    T[i][j] = T[i][j]+a[i][k]*b[k][j]
        return T
    else:
        print('Error: Invalid Matrices')

if __name__ == '__main__':
    x = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
    y = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
    print(cross_basic(x, y))
    print(cross_parallel(x, y))

这种方法可能不方便使用,例如,如果在加入进程之前没有清空队列,则可能导致程序死锁。我建议您查看multiprocessing.Poolconcurrents.futures.ProcessPoolExecutor以获得更高级别的协议,以更好的方式管理通信/流程数量。

def single_row2(a, b):
    N = len(b[0])
    output = np.zeros(N)
    for j in range(len(b[0])):
        for k in range(len(a)):
            output[j] = output[j]+a[k]*b[k][j]
    return output

def cross_parallel2(a, b):
    import itertools
    from concurrent.futures import ProcessPoolExecutor
    executor = ProcessPoolExecutor(max_workers=4)
    M = len(a)
    if len(a[0]) == len(b):
        res = executor.map(single_row2, a, itertools.repeat(b))

        return np.array([row for row in res])
    else:
        print('Error: Invalid Matrices')