Accessing Return Values from Threads
When threads are created in Python, their target function may return a value. However, retrieving this return value from the main thread is not straightforward using standard methods.
One option is to pass a mutable object, such as a list or dictionary, to the thread and store the result in a designated slot. This method requires passing additional arguments to the thread and maintaining the connection between the thread and the object.
Another approach is to subclass the Thread class and override the run and join methods. In the overridden run method, the return value of the target function is stored in a private attribute within the subclass. The overridden join method returns the value stored in this attribute.
Here's an example using the ThreadWithReturnValue subclass:
class ThreadWithReturnValue(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): Thread.__init__(self, group, target, name, args, kwargs) self._return = None def run(self): if self._target is not None: self._return = self._target(*self._args, **self._kwargs) def join(self, *args): Thread.join(self, *args) return self._return
To use this subclass:
twrv = ThreadWithReturnValue(target=foo, args=('world!',)) twrv.start() print(twrv.join()) # prints 'foo'
While this method is effective, it requires customizing the Thread class, which may not be desirable in all scenarios. Ultimately, the best approach depends on the specific needs and requirements of the application.
The above is the detailed content of How Can I Retrieve Return Values from Python Threads?. For more information, please follow other related articles on the PHP Chinese website!