【问题标题】:How to return a function value with decorator and thread如何使用装饰器和线程返回函数值
【发布时间】:2009-05-19 18:46:54
【问题描述】:

有这个代码

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))

但是函数从不返回值,退出获取返回的方法?

【问题讨论】:

  • 看起来你开始线程然后加入它。这和直接调用 add_item() 函数是一样的。

标签: python multithreading decorator


【解决方案1】:

返回None 的原因是因为没有什么可以返回(除了decorator 没有返回语句)。 join() 始终返回 None,根据 documentation

有关如何与线程通信的示例,请参阅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】:

    那是因为你永远不会在你的“装饰器”函数中返回一个值。

    您必须在线程中包含一个共享变量,并将线程函数的返回值移回“装饰器”函数。

    【讨论】:

      猜你喜欢
      • 2011-11-04
      • 2020-12-04
      • 2020-04-28
      • 2019-10-05
      • 2020-06-22
      • 2015-01-09
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多