Daccache
Daccache

Reputation: 125

Halting first execution of function on second execution (Python)

I have a function that is called when the page loads but can also be called through a button. When the page loads, the function is called - it simply waits for 15 seconds and then terminates. On the other hand, if a user presses the button before the 15 seconds are up, the function is called again and instantly terminates. Is there any way for this button press to halt the first call of the function?

#the first execution is called with the default value for the "chosen" argument.
#the second one (on button press) is always called with a non-zero value for "chosen"

def background_calculation(self, chosen=0):
    if chosen == 0:
        time.sleep(15)
        pos = np.random.randint(1, 54)
        return pos
    else:
        pos = chosen
        #I would like to stop the first function call from continuing to execute here.
        return pos

Context: background_calculation is called when a thread opens. The user has 15 seconds to make a selection, and if they do not the thread should close with a random value for pos. On the other hand, if the user makes a selection before the 15 seconds are up, the function is called and the thread is immediately ended with the user-selected value returned. At present, the function executes twice and returns two values, the user-chosen one and the randomly generated one.

What I tried: I tried using an indicator/dummy variable which points to the latest value of "chosen". At the end of the 15 seconds, the function would check if the dummy variable still points to 0 (indicating chosen was never changed) and would halt if it isn't.

Upvotes: 1

Views: 33

Answers (1)

Panwen Wang
Panwen Wang

Reputation: 3835

You probably want to maintain a global state:

button_clicked = False

def background_calculation(self, chosen=0):
    if chosen == 0:
        for i in range(15):
            time.sleep(1)
            if button_clicked: # user clicks the button
                break
        else:
            pos = np.random.randint(1, 54)
            return pos
    
    else: # chosen = 1
        global button_clicked
        button_clicked = True
        
        pos = np.random.randint(1, 54)
        return pos

Note that this implementation is just showing you how we detect the button clicking.

Warning: this is not thread-safe to be called directly.

If you only need to run only one instance at a time, you can this with a lock:

from threading import Lock

with Lock():
    background_calculation(self, chosen=0) # or 1

If you need multiple calculations to be done at the same time (from multiple users clicking the button), you need to put locks inside the function to make sure the state is set and get correctly.

Upvotes: 1

Related Questions