Python: How to get multiple return values from a threaded function

纵饮孤独 提交于 2020-06-27 08:22:08

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/50290226/python-how-to-get-multiple-return-values-from-a-threaded-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!