线程返回值

71 投票
13 回答
108859 浏览
提问于 2025-04-15 16:54

我该怎么让一个线程在Python中把一个元组或者我想要的任何值返回给父线程呢?

13 个回答

14

使用lambda来包装你想要运行的线程函数,并通过队列把它的返回值传回给主线程。这样,你原来的目标函数就不需要改动,也不用多加一个队列参数。

示例代码:

import threading
import queue
def dosomething(param):
    return param * 2
que = queue.Queue()
thr = threading.Thread(target = lambda q, arg : q.put(dosomething(arg)), args = (que, 2))
thr.start()
thr.join()
while not que.empty():
    print(que.get())

输出结果:

4
16

你应该把一个队列(Queue)的实例作为参数传进去,然后把你想返回的对象放到这个队列里,方法是用 .put()。无论你放进去什么对象,都可以通过 queue.get() 来获取返回值。

示例:

queue = Queue.Queue()
thread_ = threading.Thread(
                target=target_method,
                name="Thread1",
                args=[params, queue],
                )
thread_.start()
thread_.join()
queue.get()

def target_method(self, params, queue):
 """
 Some operations right here
 """
 your_return = "Whatever your object is"
 queue.put(your_return)

用于多个线程:

#Start all threads in thread pool
    for thread in pool:
        thread.start()
        response = queue.get()
        thread_results.append(response)

#Kill all threads
    for thread in pool:
        thread.join()

我用这个方法,效果很好。希望你也能这样做。

73

我建议你在启动线程之前先创建一个 队列,然后把它作为线程的一个参数传进去。在线程完成之前,它会把结果放到这个作为参数传入的队列里。父线程可以随时用 .get.get_nowait 来获取这个结果。

在Python中,队列通常是处理线程同步和通信的最佳方式:它们本身就是线程安全的,像是传递消息的工具——总的来说,这是组织多任务处理的最佳方法!-)

撰写回答