繁体   English   中英

在第二次执行时停止 function 的第一次执行(Python)

[英]Halting first execution of function on second execution (Python)

我有一个 function 在页面加载时调用,但也可以通过按钮调用。 当页面加载时,调用 function - 它只是等待 15 秒然后终止。 另一方面,如果用户在 15 秒结束前按下按钮,则再次调用 function 并立即终止。 按下此按钮有什么方法可以停止 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

上下文:当线程打开时调用background_calculation 用户有 15 秒的时间进行选择,如果他们不这样做,线程应该以pos的随机值关闭。 另一方面,如果用户在 15 秒结束之前做出选择,则调用 function 并立即结束线程并返回用户选择的值。 目前function执行两次,返回两个值,用户选择的一个和随机生成的一个。

我尝试了什么:我尝试使用指向“选择”的最新值的指标/虚拟变量。 在 15 秒结束时,function 将检查虚拟变量是否仍指向 0(表明所选择的从未更改过),如果不是,则会停止。

您可能想要维护一个全局 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

请注意,此实现只是向您展示我们如何检测按钮单击。

警告:直接调用这不是线程安全的。

如果您一次只需要运行一个实例,则可以使用锁:

from threading import Lock

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

如果您需要同时进行多项计算(来自多个用户单击按钮),您需要在 function 内加锁,以确保 state 设置正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM