我想创建 n 个线程,并且每个线程计算结果矩阵的一整行。我试过下面的代码,
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.]]
有人在我的代码中看到问题吗?我不明白我做错了什么。