Implement parallel matrix multiplication using threads — each thread computes one row of the result.
def validate(A, B):
if not A or not B or not A[0] or not B[0]:
raise ValueError("Matrices must be non-empty")
n, k = len(A), len(A[0])
k2, m = len(B), len(B[0])
if any (len(r) != k for r in A): raise ValueError("Matrix A is jagged")
if any (len(r) != m for r in B): raise ValueError("Matrix B is jagged")
if k != k2 :
raise ValueError("Matrices dimensions mismatch")
return n, k, m
# Compute a single row
def compute_row(i, A, B, m, k):
a_row = A[i]
return [sum(a_row[p] * B[p][j] for p in range(k)) for j in range(m)]
def multiply_serial(A,B):
n,k,m = validate(A,B)
return [compute_row(i,A,B,m,k) for i in range(n)]
print(multiply_serial(A,B))
from concurrent.futures import ThreadPoolExecutor
def multiple_threaded(A,B, max_workers=None):
n, k, m = validate(A,B)
C = [[0.0]*m for _ in range(n)]
def work(i):
C[i] = compute_row(i,A,B,m,k)
with ThreadPoolExecutor(max_workers=max_workers) as pool:
list(pool.map(work, range(n)))
return C
print(multiple_threaded(A,B))