gpt4 book ai didi

python - 如何从线程函数中获取多个返回值?

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:47 25 4
gpt4 key购买 nike

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

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,)

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

最佳答案

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

关于python - 如何从线程函数中获取多个返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com