Note that there are some explanatory texts on larger screens.

plurals
  1. POmulti-threading of a matrix multiplication in python
    text
    copied!<p>I want to create n threads and that each thread computes an entire row of the result matrix. I have tried the following code,</p> <pre><code>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) </code></pre> <p>however it prints out many weird matrices:</p> <pre><code>[ 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.]] </code></pre> <p>anyone see a problem in my code? I don't see what i am doing wrong.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload