如何从多线程调用的函数中获取多个返回值?
The issue with your current code is that threading.Thread doesn't return the output of the target function directly—threads run in the background, so you need a way to capture their results explicitly. Here are a few reliable approaches to solve this:
1. Custom Thread Subclass
You can create a subclass of threading.Thread that stores the return value of your function as an instance attribute. This gives you full control over the thread's behavior:
import threading class ResultThread(threading.Thread): def __init__(self, target, args=(), kwargs=None): super().__init__(target=target, args=args, kwargs=kwargs or {}) self.result = None def run(self): # Execute the target function and store its result if self._target is not None: self.result = self._target(*self._args, **self._kwargs) # Usage example from names import get_name full_name = "Jane Smith" # Initialize the thread with your function and arguments thread = ResultThread(target=get_name, args=(full_name,)) thread.start() # Wait for the thread to finish and retrieve the result thread.join() first_name, last_name = thread.result print(f"First: {first_name}, Last: {last_name}")
2. Use a Queue for Thread Communication
Queues are thread-safe and perfect for passing data between threads. You can wrap your function to put its result into a queue, then retrieve it once the thread finishes:
import threading from queue import Queue from names import get_name def thread_wrapper(queue, *args, **kwargs): # Call the target function and send the result to the queue result = get_name(*args, **kwargs) queue.put(result) full_name = "Bob Johnson" result_queue = Queue() # Start the thread with the wrapper and queue thread = threading.Thread(target=thread_wrapper, args=(result_queue, full_name)) thread.start() # Wait for the thread to complete thread.join() # Get the result from the queue first_name, last_name = result_queue.get() print(f"First: {first_name}, Last: {last_name}")
3. Use concurrent.futures.ThreadPoolExecutor (Simplest Option)
If you don't need low-level thread control, ThreadPoolExecutor from the concurrent.futures module provides a clean, high-level way to run functions in threads and retrieve their results:
from concurrent.futures import ThreadPoolExecutor from names import get_name full_name = "Alice Brown" # Use a context manager to handle the executor with ThreadPoolExecutor() as executor: # Submit the function to run in a thread future = executor.submit(get_name, full_name) # Wait for the result and unpack it first_name, last_name = future.result() print(f"First: {first_name}, Last: {last_name}")
Quick Notes on Each Approach:
- Custom Thread Subclass: Great if you need to extend thread behavior beyond just capturing results.
- Queue: Ideal for more complex thread communication scenarios (e.g., multiple threads sending results to a single queue).
- ThreadPoolExecutor: The most concise option for simple use cases—handles thread management automatically.
内容的提问来源于stack exchange,提问作者K K




