2009-05-19 11 views
2

このコードがどのように

import threading 
def Thread(f): 
    def decorator(*args,**kargs): 
     print(args) 
     thread = threading.Thread(target=f, args=args) 
     thread.start() 
     thread.join() 
    decorator.__name__ = f.__name__ 
    return decorator  

@Thread 
def add_item(a, b): 
    return a+b 


print(add_item(2,2)) 

を持っていますが、関数が値を返すことはありませんデコレータと糸で関数の値を返すために、リターンを得るための方法を終了?

+0

に見えますあなたがスレッドを開始してそれに参加するように。これは、add_item()関数を直接呼び出すのと同じです。 –

答えて

4

Noneが返されるのは、何も返さないためです(decoratorにはreturn文がありません)。 join()documentationのように常にNoneを返します。

スレッドとの通信方法の例については、this emailを参照してください。

join()が呼び出し元のスレッドをブロックしているので、ここで取得するのは何ですか?


編集:私は少し周りを演奏し、次のキューを必要としない解決策である(それはよりよい解決策だとは言わないだけ異なる。):

import threading 

# Callable that stores the result of calling the given callable f. 
class ResultCatcher: 
    def __init__(self, f): 
     self.f = f 
     self.val = None 

    def __call__(self, *args, **kwargs): 
     self.val = self.f(*args, **kwargs) 

def threaded(f): 
    def decorator(*args,**kargs): 
     # Encapsulate f so that the return value can be extracted. 
     retVal = ResultCatcher(f) 

     th = threading.Thread(target=retVal, args=args) 
     th.start() 
     th.join() 

     # Extract and return the result of executing f. 
     return retVal.val 

    decorator.__name__ = f.__name__ 
    return decorator 

@threaded 
def add_item(a, b): 
    return a + b 

print(add_item(2, 2)) 
2

"デコレータ"ファンクションで値を返すことはないからです。

スレッドに共有変数を含め、スレッド関数の戻り値を「デコレータ」関数に戻す必要があります。