我想创建n个线程,并且每个线程计算结果矩阵的整个行。我曾尝试下面的代码,python中的矩阵乘法的多线程
import numpy
import random
import threading
class MatrixMult(threading.Thread):
"""A thread which computes the i,j entry of A * B"""
def __init__(self, A, B, i):
super(MatrixMult, self).__init__()
self.A = A
self.B = B
self.i = i
#self.j = j
def run(self):
print "Computing %i, %i" % (self.i, self.i)
x = 0
result=[]
for k in range(self.A.shape[0])
x += self.A[self.i,k] * self.B[k,self.i
self.result=x
print "Completed %i, %i" % (self.i, self.j)
def mult(n):
"""A function to randomly create two n x n matrices and multiply them"""
# Create two random matrices
A = numpy.zeros((n,n))
B = numpy.zeros((n,n))
for i in range(n):
for j in range(n):
A[i,j] = random.randrange(0, 100)
B[i,j] = random.randrange(0, 100)
# Create and start the threads
threads = []
for i in range(n):
# for j in range(n):
t = MatrixMult(A, B, i)
threads.append(t)
t.start()
for t in threads: t.join()
C = numpy.zeros((n,n))
for t in threads:
C[t.i] = t.result
return C
print multi(30)
但它打印出许多怪异的矩阵:
[ 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695.
66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695.
66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695.
66695. 66695. 66695.]
[ 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468.
88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468.
88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468.
88468. 88468. 88468.]]
任何人看到我的代码有问题吗?我不明白我做错了什么。
假定的输出是什么? – inf 2013-03-18 23:44:42
你想在紧接着'def self(...)','x = 0'和't = MatrixMult(...)'之后的行中加入什么样的缩进? – 2013-03-18 23:45:13
这就是现在的缩进。输出很难说,因为它使随机数字,应该多个,肯定它不会看起来像这样 – 2013-03-18 23:49:23