0

I need to return two values not just print , I NEED RETURN !!!!!

for example function A :

def A(text):

    thread = threading.Thread(target=B, args=[text], kwargs={})
    thread.setDaemon(True)
    thread.start()


return "OK !!"

function B:

def B(text):
................

return result

When i do this i only get the return of A not B though i need them both

i don't have any idea how to do this with tread, that's all i know or if there are any other ways to get the result that i want please help me !!!!!! Thanks a lot

so96
  • 11
  • 2
  • Keep return inside def A() same applies on B(). Right now ur return is outside A() which terminate execution as soon as it reach to return ok then pass control to script which called A() – Lalit kumar Jul 28 '20 at 10:23
  • I think the OPs problem is not knowing how to get a return value from a thread, i.e. getting back B's result – Karl Jul 28 '20 at 10:24
  • Maybe this helps you further? https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python – mrzo Jul 28 '20 at 10:35

1 Answers1

0

I am going to take a guess and say that you are not a very experienced Python programmer (if I am wrong about that, I apologise), in which case I would warn you that parallel programming is a difficult topic (in particular if you start dealing with how to share data between threads) of which you will need to learn the key principles before having any real chance to doing it successfully. I won't go over those pricinples here, but will at least attempt to answer your concrete question about how to get a return value from a thread.

What you will need is a threadsafe construct that can be shared between threads (in this case between the main thread and the thread where you are executing "B"). The recommended way to do this is with a queue. Essentially "B" writes its result in the queue. You then pick up that result afterwards, as follows:

import queue
import threading


def b(arg1, arg2, q):
    q.put(arg1+arg1)

def a(arg1, arg2):
    q = queue.Queue() # Define a queue with which to share data between threads.

    thread = threading.Thread(target=b, args=(arg1,arg1,q)) # define thread
    thread.start() # start thread
    thread.join() # wait for thread to finish before continuing
    
    item=q.get() # get the top item from the queue. In this case there will be only one item
    q.task_done() # remove the top item from the queue. Generelly this is necessary, in your case you don't need it

    return "OK", item    

ok, item= a(1,2)
print(item)
Karl
  • 5,573
  • 8
  • 50
  • 73