问题描述
我正在尝试理解 python 中的多处理.
I'm trying to understand multiprocessing in python.
from multiprocessing import Process
def multiply(a,b):
print(a*b)
return a*b
if __name__ == '__main__':
p = Process(target= multiply, args= (5,4))
p.start()
p.join()
print("ok.")
在这个代码块中,例如,如果有一个名为结果"的变量.如何将乘法函数的返回值赋给结果"?
In this codeblock, for example, if there was an variable that called "result". How can we assign return value of multiply function to "result"?
还有一个关于 IDLE 的小问题:当我尝试使用 Python Shell 运行此示例时,它无法正常工作?如果我双击 .py 文件,输出是这样的:
And a little problem about IDLE: when i'm tried to run this sample with Python Shell, it doesn't work properly? If i double click .py file, output is like that:
20
ok.
但如果我尝试在 IDLE 中运行它:
But if i try to run this in IDLE:
ok.
谢谢...
推荐答案
好的,我设法做到了.我查看了 python 文档,我了解到:使用 Queue
类,我们可以从函数中获取返回值.我的代码的最终版本是这样的:
Ok, i somehow managed this. I looked to python documentation, and i learnt that: with using Queue
class, we can get return values from a function. And final version of my code is like this:
from multiprocessing import Process, Queue
def multiply(a,b,que): #add a argument to function for assigning a queue
que.put(a*b) #we're putting return value into queue
if __name__ == '__main__':
queue1 = Queue() #create a queue object
p = Process(target= multiply, args= (5,4,queue1)) #we're setting 3rd argument to queue1
p.start()
print(queue1.get()) #and we're getting return value: 20
p.join()
print("ok.")
还有一个 pipe()
函数,我想我们也可以使用 pipe()
函数.但是 Queue
现在对我有用了.
And there is also a pipe()
function, i think we can use pipe()
function,too. But Queue
worked for me, now.
这篇关于使用多处理将函数的返回值分配给变量?关于 IDLE 的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!