简体   繁体   English

从multiprocessing.process获取结果进行循环

[英]Getting results from multiprocessing.process for a loop

The goal of this program is to calculate the loop_random for the loop num . 该程序的目标是计算循环numloop_random I want to calculate 4 random different num/4 with 4 processors in parallel and in the end summing to give the u_total . 我想用4个处理器并行计算4个随机不同的num/4 ,最后求和得出u_total But the problem is though I see all the 4 processors in action, the end result is calculated for 4 times the same set of num/4 . 但是问题是尽管我看到所有4个处理器都在工作,但最终结果是为相同的num/4集计算4倍的。 But I want to calculate loop_random for 4 different random arrays. 但是我想为4个不同的随机数组计算loop_random Here is the snippet of the part of the code I am working on. 这是我正在处理的部分代码的片段。 .

from numpy import *
import multiprocessing as mp
from multiprocessing import Process, Queue
num = 5000
def loop_random(num, out):
    n = 1
    total = zeros(((100.,100.,100.)), dtype='float')
    while n<= num:
        x, y , z = random.rand(100), random.rand(100), random.rand(100) #some random numbers
        result = x**2 + y**2 + z**2
        total = total + result
        n += 1
    out.put(total)

if __name__=='__main__':
    q1 = mp.Queue()
    q2 = mp.Queue()
    q3 = mp.Queue()
    q4 = mp.Queue()
    p1 = mp.Process(target = loop_random, args=(num/4, q1))
    p2 = mp.Process(target = loop_random, args=(num/4, q2))
    p3 = mp.Process(target = loop_random, args=(num/4, q3))
    p4 = mp.Process(target = loop_random, args=(num/4, q4))
    p1.start()
    p2.start()
    p3.start()
    p4.start()
    u_total_proc1 = q1.get()
    u_total_proc2 = q2.get()
    u_total_proc3 = q3.get()
    u_total_proc4 = q4.get()
    p1.join()
    p2.join()
    p3.join()
    p4.join()
    u_total = u_total_proc1 + u_total_proc2 + u_total_proc3 + u_total_proc4
    print u_total

Any suggestions are welcome. 欢迎任何建议。 The problem is more about is this the right way of multiprocessing? 问题更多在于这是正确的多处理方式吗? Does each Queue calculate the same result and not stored or each processor calculates different results and stored? 是每个队列计算出相同的结果并没有存储,还是每个处理器计算出不同的结果并存储? Thanks a lot for your help. 非常感谢你的帮助。 Please do correct me if there is something wrong in what I said. 如果我所说的话有误,请纠正我。

Sorry for posting this answer, as it is not an answer, however I cannot post comments yet. 很抱歉张贴此答案,因为它不是答案,但是我还不能发表评论。

Just wanted to note that using: 只是要注意使用:

from pylab import *

Is considered bad practise. 被认为是坏习惯。 Don't blanket import a bunch of random stuff. 不要毯子导入一堆随机的东西。 Each module should have a longish list of the specific things it needs. 每个模块都应详细列出其所需的具体内容。

According to the Python Zen: 根据Python Zen:

Explicit is better than implicit. 显式胜于隐式。

Can't argue with that :) 不能与之争论:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM