我有一个函数def act(obs),它返回一个浮点,在计算上非常昂贵(运行起来需要一些时间)。
import time
import random
def act(obs):
    time.sleep(5) # mimic computation time
    action = random.random()
    return action我经常在脚本中调用这个函数,速度比执行它所需的时间还要快。在调用函数时,我不希望有任何等待时间。相反,我更喜欢使用早期计算中返回的值。我怎样才能做到这一点?
我想到的是有一个在函数中更新的全局变量,我一直在阅读全局变量,尽管我不确定这是否是实现它的最佳方法。
发布于 2022-01-02 13:46:35
这就是我最后使用的基于this answer的
class MyClass:
    def __init__(self):
        self.is_updating = False
        self.result = -1
    
    def _act(self, obs):
        self.is_updating = True
        time.sleep(5)
        self.result = obs
        self.is_updating = False
        
    def act(self, obs):
        if not self.is_updating:
            threading.Thread(target=self._act, args=[obs]).start()
        return self.result
agent = MyClass()
i = 0
while True:
    agent.act(obs=i)
    time.sleep(2)
    print(i, agent.result)
    i += 1发布于 2022-01-02 13:31:23
全局变量方法应该可以工作,还可以有一个具有私有成员的类--比如result和一个标志isComputing和一个方法getResult --如果它当前没有计算,它将调用一个方法compute()(通过线程),并返回前面的结果。compute()方法应该正确地更新标志isComputing。
https://stackoverflow.com/questions/70556285
复制相似问题