【发布时间】:2014-12-14 00:56:18
【问题描述】:
我正在做一个学期末的项目,我需要能够将矩阵发挥到极致,并且我需要使问题成为多线程的。
此代码在某些情况下有效,但在其他情况下无效。我相信它与 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 变量时,会遇到无法正确计算的问题。
感谢您的宝贵时间。
【问题讨论】:
-
我认为您使用
numpy会走得更远——它在内部使用 BLAS 库,该库经过高度优化,可以在内部编译为多线程,速度要快得多(实际上可能是三个或更多命令比你在原始 Python 中可以做的任何事情都要快。 -
numCalc是做什么的? -
numCalc 应该确定每个线程应该执行的计算次数。我试图用它来做开始和结束索引,但我认为我的数学在这里的某个地方是错误的。
标签: python multithreading matrix matrix-multiplication