Python多线程矩阵乘法

时间:2014-12-14 00:56:19

标签: python multithreading matrix matrix-multiplication

我正在为学期结束做一个项目,我需要能够将矩阵用于电源,我需要将问题解决为多线程。

此代码适用于某些情况,而不适用于其他情况。我相信它与process_data函数中的嵌套循环中的逻辑有关,但我不确定我做错了什么!我已经在这个工作了几个星期,我绝对难过。看起来它与我的线程超出范围有关,但即便如此我也不太确定,因为在某些情况下线程超出界限但仍能正确计算矩阵。

请帮忙!

import copy
import numpy
import Queue
import random
import threading
import time
import timeit

# Create variable that determines the number of columns and
# rows in the matrix.
n = 4

# Create variable that determines the power we are taking the
# matrix to.
p = 2

# Create variable that determines the number of threads we are
# using.
t = 2

# Create an exit flag.
exitFlag = 0

# Create threading class.
class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print "Starting " + self.name
        process_data(self.name, self.q)
        print "Exiting " + self.name

# Create a function that will split our data into multiple threads
# and do the matrix multiplication.
def process_data(threadName, q):
    numCalc = ((n^3)/t)
    for a in range(p-1):
        for b in range((numCalc*(q-1)),(numCalc*(q))):
            for c in range(n):
                for d in range(n):
                    matrix[a+1][b][c] += matrix[a][b][d] * matrix[0][d][c]

# Create a three dimensional matrix that will store the ouput for
# each power of the matrix multiplication.
matrix = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(p)]
print matrix

# This part fills our initial n by n matrix with random numbers
# ranging from 0 to 9 and then prints it!
print "Populating Matrix!"
for i in range(n):
    for j in range(n): 
        matrix[0][i][j] = random.randint(0,9)

# Tells the user that we are multiplying matrices and starts the
# timer.
print "Taking our matrix to the next level!"
start = timeit.default_timer()
threadLock = threading.Lock()

threads = []
threadID = 1

# Create new threads
for tName in range(t):
    thread = myThread(threadID, "Thread-0"+str(tName), threadID)
    thread.start()
    threads.append(thread)
    threadID += 1
# Wait for all threads to complete
for x in threads:
    x.join()

stop = timeit.default_timer()
print stop - start 
print "Exiting main thread!"
print matrix

矩阵平方似乎在每种情况下都有效,但是如果我试图计算超出其余,那么剩余的能量就会出现用零填充的矩阵!我发布的案例有效。

当我更改n,p和t变量时,我遇到了无法正常计算的问题。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

这是不正确的:

numCalc = ((n^3)/t)

  for b in range((numCalc*(q-1)),(numCalc*(q))):

例如,当n = 4且t = 2时,第一个线程应该在列[0,1]上具有b范围,在列[2,3]上具有第二个线程范围。但是这个计算给出了:

numCalc = 8 / 2 = 4
thread 1 ranges b over range(0, 4) = [0,1,2,3]
thread 2 ranges b over range(4, 8) = [4,5,6,7]

因此,线程1执行所有工作,线程2尝试访问不存在的列!