【问题标题】:Python: How to get multiple return values from a threaded functionPython:如何从线程函数中获取多个返回值
【发布时间】:2018-10-21 17:56:00
【问题描述】:

调用了一个返回多个值的外部函数。

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

在简单的函数调用中,我可以得到结果。

from names import get_name

first, last= get_name(full_name)

但我需要对调用使用线程来获取第一个和最后一个变量的结果值。我未能使用简单的线程调用。

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

请帮我获取函数调用的返回值

【问题讨论】:

  • 使用队列并将它们放到那里而不是返回它们。
  • 失败的本质是什么?如果遇到错误,能否发布堆栈跟踪信息?

标签: python multithreading multiprocessing


【解决方案1】:

您应该使用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)

这里有live working example

【讨论】:

  • 感谢您的帮助。
  • 这太过分了,concurrent.futures 会更好
猜你喜欢
  • 2011-10-17
  • 2018-04-15
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多