Skip to content

Thread with result

ThreadWithReturnValue

Bases: Thread

A thread can save the target func exec result.

Source code in agentuniverse/agent_serve/web/thread_with_result.py
Python
class ThreadWithReturnValue(Thread):
    """A thread can save the target func exec result."""
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None):
        super().__init__(group, target, name, args, kwargs)

        if kwargs is None:
            kwargs = {}
        self.kwargs = kwargs
        self.args = args
        self.target = target
        self._return = None
        self.error = None

    def run(self):
        """Run the target func and save result in _return."""
        if self.target is not None:
            try:
                self._return = self.target(*self.args, **self.kwargs)
            except Exception as e:
                self.error = e

    def result(self):
        """Wait for target func finished, then return the result or raise an
        error."""
        self.join()
        if self.error is not None:
            raise self.error
        return self._return

result()

Wait for target func finished, then return the result or raise an error.

Source code in agentuniverse/agent_serve/web/thread_with_result.py
Python
def result(self):
    """Wait for target func finished, then return the result or raise an
    error."""
    self.join()
    if self.error is not None:
        raise self.error
    return self._return

run()

Run the target func and save result in _return.

Source code in agentuniverse/agent_serve/web/thread_with_result.py
Python
def run(self):
    """Run the target func and save result in _return."""
    if self.target is not None:
        try:
            self._return = self.target(*self.args, **self.kwargs)
        except Exception as e:
            self.error = e