如何使用装饰器和线程返回函数值
我有这段代码
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))
但是这个函数从来没有返回值,有没有办法让它返回呢?
2 个回答
2
这是因为你在你的“装饰器”函数里没有返回任何值。
你需要在你的线程中包含一个共享变量,并把你线程函数的返回值传回到“装饰器”函数里。
4
返回None
的原因是因为没有东西可以返回(再加上decorator
没有返回语句)。join()
总是返回None
,这是根据文档的说明。
如果你想看看如何与线程进行通信,可以参考这封邮件。
不过我想问一下:既然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))