我在 numpy 数组中有参数集,我将它们输入到多处理队列中,但是在工作进程中收到它们时会出现乱码。这是我的代码来说明我的问题。
import numpy as np
from multiprocessing import Process, Queue
NUMBER_OF_PROCESSES = 2
def worker(input, output):
for args in iter(input.get, 'STOP'):
print('Worker receives: ' + repr(args))
id, par = args
# simulate a complex task, and return result
result = par['A'] * par['B']
output.put((id, result))
# Define parameters to process
parameters = np.array([
(1.0, 2.0),
(3.0, 3.0)], dtype=[('A', 'd'), ('B', 'd')])
# Create queues
task_queue = Queue()
done_queue = Queue()
# Submit tasks
for id, par in enumerate(parameters):
obj = ('id_' + str(id), par)
print('Submitting task: ' + repr(obj))
task_queue.put(obj)
# Start worker processes
for i in range(NUMBER_OF_PROCESSES):
Process(target=worker, args=(task_queue, done_queue)).start()
# Get unordered results
results = {}
for i in range(len(parameters)):
id, result = done_queue.get()
results[id] = result
# Tell child processes to stop
for i in range(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
print('results: ' + str(results))
在 64 位 CentOS 计算机上使用 numpy 1.4.1 和 Python 2.6.6,我的输出是:
Submitting task: ('id_0', (1.0, 2.0))
Submitting task: ('id_1', (3.0, 3.0))
Worker receives: ('id_0', (2.07827093387802e-316, 6.9204740511333381e-310))
Worker receives: ('id_1', (0.0, 1.8834810076011668e-316))
results: {'id_0': 0.0, 'id_1': 0.0}
如图所示,带有numpy记录数组的元组在提交任务时状态良好,但在worker收到参数时出现乱码,结果不正确。我在multiprocessing
文档中读到“代理方法的参数是可选的”。据我所知,numpy 数组是完全可以挑选的:
>>> import pickle
>>> for par in parameters:
... print(pickle.loads(pickle.dumps(par)))
...
(1.0, 2.0)
(3.0, 3.0)
我的问题是为什么工人没有正确接收参数?我怎样才能将一行 numpy 记录数组传递给工作人员?