Python 戻り値ありのスレッドの方法というのをネット検索すると
やたらと Future の使用を見かけます。
from concurrent.futures import ThreadPoolExecutor
ThreadPoolExecutor の submit メソッド呼び出しで Future を受け取って
Future の result メソッドで取得する。
確かにこれはよく一般的に良く使われる方法ではあるのだけれど、
厳密に1つのスレッド限定したものではない。
threading.Thread を継承して join がスレッドの結果を返す
クラスを用意する。
returableThread.py
# -*- coding: utf-8 -*- from threading import Thread class ReturableThread(Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): Thread.__init__(self, group, target, name, args, kwargs) def run(self): if self._target != None: self._return = self._target(*self._args, **self._kwargs) def join(self, *args, **kwargs): Thread.join(self, *args, **kwargs) return self._return
join() で受け取る サンプル
import time import threading from returableThread import ReturableThread def multiply(val: int) -> int: print("[%s] -- mutiply val = %d\n" % (threading.current_thread(), val)) time.sleep(2) return val * 2 #------------------------------------------ if __name__ == "__main__": thread = ReturableThread(target=multiply, name=('thread-A'), args=(12,)) print("[%s] -- call ReturableThread " % threading.current_thread()) thread.start() result = thread.join() print("[%s] -- join ReturableThread" % threading.current_thread()) print("result = %s" % result)
結果
[<_MainThread(MainThread, started 16900)>] -- call ReturableThread [<ReturableThread(thread-A, started 12544)>] -- mutiply val = 12 [<_MainThread(MainThread, started 16900)>] -- join ReturableThread result = 24