您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使进程能够在主程序的数组中编写?

如何使进程能够在主程序的数组中编写?

矩阵乘法是指分别计算所得矩阵的每个元素。对于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)

同样,代码的确切形状取决于您如何表示矩阵。

其他 2022/1/1 18:52:18 有422人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶