Skip to content

Instantly share code, notes, and snippets.

@nitori
Created June 15, 2023 11:43
Show Gist options
  • Select an option

  • Save nitori/a062f884901c1d61210b3539e519bc80 to your computer and use it in GitHub Desktop.

Select an option

Save nitori/a062f884901c1d61210b3539e519bc80 to your computer and use it in GitHub Desktop.
Simple subclass of threading.Thread that returns the targets return value on join
from typing import Callable, Any
from threading import Thread
from concurrent.futures import Future
class ReturnThread(Thread):
_target: Callable
_args: tuple[Any, ...]
_kwargs: dict[str, Any]
_fut: Future
def start(self):
self._fut = Future()
super().start()
def run(self):
try:
result = None
# taken from parent method, except result is stored.
if self._target is not None:
result = self._target(*self._args, **self._kwargs)
except Exception as exc:
self._fut.set_exception(exc)
else:
self._fut.set_result(result)
finally:
# taken from parent method
del self._target, self._args, self._kwargs
def join(self, timeout=None):
super().join(timeout)
if exc := self._fut.exception():
raise exc
return self._fut.result()
def foobar(n):
return n * 2
def main():
t1 = ReturnThread(target=foobar, args=(1,))
t2 = ReturnThread(target=foobar, args=(2,))
t3 = ReturnThread(target=foobar, args=(3,))
t1.start()
t2.start()
t3.start()
print(t1.join()) # 2
print(t2.join()) # 4
print(t3.join()) # 6
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment