【问题标题】:Python parallel array generationPython并行数组生成
【发布时间】:2025-12-04 17:10:02
【问题描述】:

我想生成并行 2 两个数组,即。 e. x1x2 用于进一步分析(比较来自 x1 的最大值元素与来自 x2 的最大值元素)。 程序的开头是这样的

import multiprocessing
import numpy as np


while true:

   x1 = np.random.normal(0, 500, 12500)
   x2 = np.random.normal(0, 500, 12500)

   if(x1...x2): #condition comparing elements from array x1 and x2
      break

print('Number found)'

我试着像这样重写它

import multiprocessing
import numpy as np

def gen():

   np.random.normal(0, 500, 12500)

while true:

   x1 = multiprocessing.Process(target=gen, arg=())
   x2 = multiprocessing.Process(target=gen, arg=())

   x1.start()
   x2.start()

   x1.join()
   x2.join()

   if(x1...x2): #condition comparing elements from array x1 and x2
      break

print('Number found)'

但程序不会并行生成随机数组 x1、x2。谢谢你的帮助。

【问题讨论】:

  • 您知道gen 不返回任何内容,也不分配给全局变量

标签: arrays python-3.x parallel-processing multiprocessing python-multiprocessing


【解决方案1】:

x1x2 在您的第二个示例进程中,您需要实现一个队列 像这样的东西可以工作

import multiprocessing
import numpy as np

def gen(q):
   x = np.random.normal(0, 500, 12500)
   q.put(x)

while true:
   q = multiprocessing.Queue()
   x1 = multiprocessing.Process(target=gen, arg=(q,))
   x2 = multiprocessing.Process(target=gen, arg=(q,))

   x1.start()
   x2.start()
   y1 = q.get()
   y2 = q.get()
   x1.join()
   x2.join()
   if(y1...y2): #condition comparing elements from array y1 and y2
      break

【讨论】:

  • 应该是 'args' 而不是 'arg'