返回原因None
,是因爲沒有什麼可返回的(除了decorator
沒有返回語句的事實)。根據documentation,join()
總是返回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))
它看起來就像你開始線程然後加入它一樣。這與直接調用add_item()函數相同。 – 2009-05-19 18:55:47