Home > Back-end >  Python asynchronous call that updates a variable
Python asynchronous call that updates a variable

Time:01-03

I have a function def act(obs) that returns a float and is computationally expensive (takes some time to run).

import time
import random

def act(obs):
    time.sleep(5) # mimic computation time
    action = random.random()
    return action

I regularly keep calling this function in a script faster than how long it takes for it to execute. I do not want any waiting time when calling the function. Rather I prefer using the returned value from an earlier computation. How do I achieve this?

Something I have thought of is having a global variable that updated in the function and I keep reading the global variable although I am not sure if that is the best way to achieve it.

CodePudding user response:

This is what I ended up using based on 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

CodePudding user response:

The global variable way should work, Also you can have a class that has a private member let's say result and a flag isComputing and a method getResult which would call a method compute()(via a thread) if it is not computing currently, and returns the previous result. The compute() method should update the flag isComputing properly.

  • Related