矩阵乘法是指分别计算所得矩阵的每个元素。对于Pool来说,这似乎是一份工作。由于这是家庭作业(还要遵循SO代码),因此我仅说明Pool本身的用法,而不是整个解决方案。
因此,您必须编写一个例程来计算所得矩阵的第(i,j)个元素:
def getProductElement(m1, m2, i, j):
# some calculations
return element
然后初始化池:
from multiprocessing import Pool, cpu_count
pool = Pool(processes=cpu_count())
然后,您需要提交工作。您也可以将它们组织成矩阵,但是为什么麻烦,让我们列出一个清单。
result = []
# here you need to iterate through the the columns of the first and the rows of
# the second matrix. How you do it, depends on the implementation (how you store
# the matrices). Also, make sure you check the dimensions are the same.
# The simplest case is if you have a list of columns:
N = len(m1)
M = len(m2[0])
for i in range(N):
for j in range(M):
results.append(pool.apply_async(getProductElement, (m1, m2, i, j)))
然后用结果填充结果矩阵:
m = []
count = 0
for i in range(N):
column = []
for j in range(M):
column.append(results[count].get())
m.append(column)
同样,代码的确切形状取决于您如何表示矩阵。