python 多线程并行 矩阵乘法_Python多线程矩阵乘法

我正在做一个学期末的专题,我需要能够把一个矩阵的幂次,我需要使问题多线程。在

此代码在某些情况下有效,而在其他情况下则不行。我相信这与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变量时,我遇到了计算不正确的问题。在

谢谢你抽出时间。在

你可能感兴趣的:(python,多线程并行,矩阵乘法)