2009-05-19 60 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()函數相同。 – 2009-05-19 18:55:47

回答

4

返回原因None,是因爲沒有什麼可返回的(除了decorator沒有返回語句的事實)。根據documentationjoin()總是返回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

這是因爲你永遠不會在你的「裝飾器」功能中返回一個值。

您必須在您的線程中包含共享變量,並將線程函數的返回值移回「裝飾器」函數。