如何使进程能够写入主程序的数组? [英] How do I make processes able to write in an array of the main program?

查看:20
本文介绍了如何使进程能够写入主程序的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个进程池,每个进程池都需要写入主程序中存在的矩阵的不同部分.无需担心覆盖信息,因为每个进程都将使用矩阵的不同行.如何在进程中使矩阵可写?

I am making a process pool and each of them need to write in different parts of a matrix that exists in the main program. There exists no fear of overwriting information as each process will work with different rows of the matrix. How can i make the matrix writable from within the processes??

该程序是一位教授分配给我的矩阵乘法器,必须进行多重处理.它将为计算机拥有的每个核心创建一个进程.主程序将矩阵的不同部分发送给进程,它们将计算它们,然后它们将以一种方式返回它们,我可以确定哪个响应对应于它基于的哪一行.

The program is a matrix multiplier a professor assigned me and has to be multiprocessed. It will create a process for every core the computer has. The main program will send different parts of the matrix to the processes and they will compute them, then they will return them in a way i can identify which response corresponds to which row it was based on.

推荐答案

矩阵乘法意味着结果矩阵的每个元素单独计算.这似乎是 Pool 的工作.由于这是家庭作业(并且还要遵循 SO 代码),我将仅说明 Pool 本身的使用,而不是整个解决方案.

Matrix multiplication means each element of the resulting matrix is calculated separately. That seems like a job for Pool. Since it's homework (and also to follow the SO code) I will only illustrate the use of the Pool itself, not the whole solution.

因此,您必须编写一个例程来计算结果矩阵的第 (i, j) 个元素:

So, you have to write a routine to calculate the (i, j)-th element of the resulting matrix:

def getProductElement(m1, m2, i, j):
    # some calculations
    return element

然后初始化池:

from multiprocessing import Pool, cpu_count
pool = Pool(processes=cpu_count())

然后您需要提交作业.您也可以将它们组织成矩阵,但何必呢,让我们列个清单吧.

Then you need to submit the jobs. You can organize them in a matrix, too, but why bother, let's just make a list.

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)))

然后用结果填充结果矩阵:

Then fill the resulting matrix with the results:

m = []
count = 0
for i in range(N):
    column = []
    for j in range(M):
        column.append(results[count].get())
    m.append(column)

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

Again, the exact shape of the code depends on how you represent the matrices.

这篇关于如何使进程能够写入主程序的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆