Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

python - Assigning return value of function to a variable, with multiprocessing? And a problem about IDLE?

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"?

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.

But if i try to run this in IDLE:

ok.

Thanks...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.")

And there is also a pipe() function, i think we can use pipe() function,too. But Queue worked for me, now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...