0
在下面的代碼中,我從用戶獲得兩個矩陣,並嘗試計算兩個矩陣與thread
的乘法。我是新的thread
,我不知道爲什麼thread
部分代碼無法運行?爲什麼此代碼的線程部分不運行
我的問題是線程部分代碼的問題在哪裏?
import threading
from queue import Queue
import time
import numpy as np
# get the number of rows and columns
r1, c1 = int(input("Enter the number of rows in matrix 1: ")), int(input("Enter the number of columns in matrix 1: "))
#initialize the matrix 1 with 0
matrix1 = np.zeros((r1,c1))
# get the matrix elements from user
for i in range(r1):
for j in range(c1):
matrix1[i][j] = int(input('enter element matrix[{}][{}]: '.format(i, j)))
# get the number of rows and columns
r2, c2 = int(input("Enter the number of rows in matrix 2: ")) , int(input("Enter the number of columns in matrix 2: "))
#initialize the matrix 2 with 0
matrix2 = np.zeros((r2, c2))
# get the matrix elements from user
for i in range(r2):
for j in range(c2):
matrix2[i][j] = int(input('enter element matrix[{}][{}]: '.format(i, j)))
print("matrix 1", matrix1)
print("matrix 2", matrix2)
# initializing the result matrix with 0
res_matrix = np.zeros((r1,c2))
q = Queue()
# multiply matrices using thread
def mat_mult(t):
i = t[0]
j = t[1]
for a in range(c1):
res_matrix[i][j] += matrix1[i][a] * matrix2[a][j]
print(res_matrix)
def threader():
while True:
worker = q.get()
#this print is just for checking if the threader function running
print("******",worker)
mat_mult(worker)
q.task_done()
# Create threads in number of elements of result matrix
for worker in range(r1 * c2):
t = threading.Thread(target= threader())
t.daemon = True
t.start()
start = time.time()
for i in range(r1):
for j in range(c2):
t= (i,j)
q.put((t))
q.join()
print(time.time()-start)
,當我運行的代碼,並給出了兩個矩陣進行編程,程序仍然沒有輸出運行,但是當我手動終止它,我得到這個:
Enter the number of rows in matrix 1: 2
Enter the number of columns in matrix 1: 3
enter element matrix[0][0]: 1
enter element matrix[0][1]: 2
enter element matrix[0][2]: 3
enter element matrix[1][0]: 4
enter element matrix[1][1]: 5
enter element matrix[1][2]: 6
Enter the number of rows in matrix 2: 3
Enter the number of columns in matrix 2: 2
enter element matrix[0][0]: 7
enter element matrix[0][1]: 8
enter element matrix[1][0]: 9
enter element matrix[1][1]: 10
enter element matrix[2][0]: 11
enter element matrix[2][1]: 12
matrix 1 [[ 1. 2. 3.]
[ 4. 5. 6.]]
matrix 2 [[ 7. 8.]
[ 9. 10.]
[ 11. 12.]]
Traceback (most recent call last):
File "/Users/saman/PycharmProjects/Syslab/test.py", line 46, in <module>
t = threading.Thread(target= threader())
File "/Users/saman/PycharmProjects/Syslab/test.py", line 40, in threader
worker = q.get()
File "/Applications/anaconda/lib/python3.5/queue.py", line 164, in get
self.not_empty.wait()
File "/Applications/anaconda/lib/python3.5/threading.py", line 293, in wait
waiter.acquire()
KeyboardInterrupt