8

Have called an external function which returns multiple values.

def get_name(full_name):
   # you code
   return first_name, last_name

In simple function call, I can get the results.

from names import get_name

first, last= get_name(full_name)

But I need to use threading for the call to get the result values for the first and last variables. I failed in using a simple threading call.

first, last= Threading.thread(get_name, args= (full_name,)

Please help me to get the return values of the function call

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
K K
  • 363
  • 3
  • 6
  • 15
  • 1
    using a queue and pusing them there instead of returning them. – Netwave May 11 '18 at 10:28
  • What was the nature of the failure exactly? If you got an error, could you post the stack trace? – Mad Physicist May 11 '18 at 10:47
  • Does this answer your question? [How to get the return value from a thread in Python?](https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python) – Arik May 06 '22 at 14:53

2 Answers2

13

You should use a queue for retrieve data from threads, here you have an example using a wrapper to store values from the functions into a queue:

import threading
import queue

my_queue = queue.Queue()

def storeInQueue(f):
  def wrapper(*args):
    my_queue.put(f(*args))
  return wrapper


@storeInQueue
def get_name(full_name):
   return full_name, full_name



t = threading.Thread(target=get_name, args = ("foo", ))
t.start()

my_data = my_queue.get()
print(my_data)

Here you have the live working example

Netwave
  • 40,134
  • 6
  • 50
  • 93
1

You can use pool.apply_async() of ThreadPool() to return the multiple values from test() as shown below:

from multiprocessing.pool import ThreadPool

def test(arg1, arg2):
    return 'a', 1, arg1, arg2

pool = ThreadPool(processes=1) # Here
result = pool.apply_async(test, ('b', 2)) # Here
print(result.get()) # ('a', 1, 'b', 2)

And, you can also use submit() of concurrent.futures.ThreadPoolExecutor() to return the multiple values from test() as shown below:

from concurrent.futures import ThreadPoolExecutor

def test(arg1, arg2):
    return 'a', 1, arg1, arg2

with ThreadPoolExecutor() as executor: # Here
    future = executor.submit(test, 'b', 2) # Here
    print(future.result()) # ('a', 1, 'b', 2)
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129