一旦其中一个完成,如何获取多线程的 return 值?

How to get return values of multi threads once one of them is finished?

我想要五个函数 运行 同时使用 python 线程。这些函数中的每一个 return 都是一个值。我想在这些函数完成工作后获得它们的 return 值。我实现了以下等待线程顺序加入的代码。换句话说,当代码等待 thread1 加入时,thread2 可能会完成它的工作并且 return 一个值。但是,我想首先获得完成其工作的第一个线程 return 值,然后获得完成其工作的第二个线程的值,依此类推。

threads = []
for user in users:
    task = threading.Thread(target=monitor_wrapper, args=(user[0], user[1]))
    threads.append(task)
    task.start()
    time.sleep(delay / len(users))
for thread in threads:
    result = thread.join()
    print(result)

关于这件事,我阅读了一些关于 Queue 的内容。

的确,您可以让线程将它们的结果放入队列中 (queue.put) while the main thread waits for results from the queue (queue.get)。顺便说一下,这是线程安全的 class。

官方文档:https://docs.python.org/3/library/queue.html

您可以使用 multiprocessing.pool.ThreadPool with its starmap 函数:

from multiprocessing.pool import ThreadPool

with ThreadPool(len(users)) as pool:
    results = pool.starmap(monitor_wrapper, users)

我相信这说明了如何做你想做的事。它使用 appy_async() method that the multiprocessing.pool.ThreadPool class ,因此它可以指定一个回调函数,该函数为其提供了向结果添加完成时间以及捕获结果的机会。在示例代码中,结果本身包括参数以及一个随机结果值,以便能够识别每个虚假结果的来源。

from multiprocessing.pool import ThreadPool
import random
import threading
import time

def monitor_wrapper(*args):
    time.sleep(random.uniform(1.0, 2.0))
    return args + (random.randint(1, 100),)

if __name__ == '__main__':

    results = []
    users = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]

    def callback(result):
        results.append((result, time.time()))  # Add finish time to result.

    with ThreadPool(processes=3) as pool:
        for user in users:
            pool.apply_async(monitor_wrapper, user, callback=callback)
        pool.close()  # All tasks submitted.
        pool.join()  # Wait for the worker processes to exit.

    results.sort(key=lambda t: t[1])  # Sort results by finish time.

    print('Results in order of finishing time:')
    for result in results:
        print(f'  users: {result[0][:2]}, returned value: {result[0][2]}, '
              f' finishing time: {result[1]}')

这是一些示例输出:

Results in order of finishing time:
  users: ('e', 'f'), returned value: 29,  finishing time: 1630452226.8134956
  users: ('c', 'd'), returned value: 67,  finishing time: 1630452226.9075007
  users: ('a', 'b'), returned value: 47,  finishing time: 1630452227.0395086
  users: ('g', 'h'), returned value: 97,  finishing time: 1630452228.1155698