Home >Backend Development >Python Tutorial >How Can I Retrieve Return Values from Python Threads?

How Can I Retrieve Return Values from Python Threads?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 06:10:26578browse

How Can I Retrieve Return Values from Python Threads?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn