我想創建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