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

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

问题描述

我正在创建一个进程池,并且每个进程都需要写入主程序中存在的矩阵的不同部分.不必担心会覆盖信息,因为每个进程将与矩阵的不同行一起工作.如何使矩阵在过程中可写?

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.

推荐答案

矩阵乘法是指分别计算所得矩阵的每个元素.这似乎是游泳池的工作.既然是家庭作业(还要遵循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天全站免登陆