我正在尝试理解 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 的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Python 多处理模块的 .join() 方法到底在做什么?What exactly is Python multiprocessing Module#39;s .join() Method Doing?(Python 多处理模块的 .join() 方法到底在做什么?)
在 Python 中将多个参数传递给 pool.map() 函数Passing multiple parameters to pool.map() function in Python(在 Python 中将多个参数传递给 pool.map() 函数)
multiprocessing.pool.MaybeEncodingError: 'TypeError("multiprocessing.pool.MaybeEncodingError: #39;TypeError(quot;cannot serialize #39;_io.BufferedReader#39; objectquot;,)#39;(multiprocessing.pool.MaybeEnc
Python 多进程池.当其中一个工作进程确定不再需要Python Multiprocess Pool. How to exit the script when one of the worker process determines no more work needs to be done?(Python 多进程池.当其中一
如何将队列引用传递给 pool.map_async() 管理的函数How do you pass a Queue reference to a function managed by pool.map_async()?(如何将队列引用传递给 pool.map_async() 管理的函数?)
与多处理错误的另一个混淆,“模块"对象没yet another confusion with multiprocessing error, #39;module#39; object has no attribute #39;f#39;(与多处理错误的另一个混淆,“模块对象