锁的python问题

2024-10-01 17:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码试图暂停一个特定的操作。我有一个暂停应用程序的方法和另一个在某个超时值后恢复应用程序的方法。为了实现这一点,我有一个定时线程,它以固定的时间间隔运行

考虑以下方法-

def pause_my_operation():
     with self._lock:
         # check if there is already an existing timer, if present then cancel the timer and start a new timer
         # pause the operation

def pausetimeout():
    with self._lock:
        # check if there is already an existing timer, if present then cancel it.
        # resume the operation

该操作在UI中有两个可以暂停的位置。因此,在pause方法中检查计时器

现在,我面临的问题是,这两个函数之间可能存在竞争。如果第一个暂停提前一段时间触发,并且即将过期,即pausetimeout of first pause刚刚进入方法,但在获得锁之前,UI会再次调用暂停操作,即。,暂停我的操作被调用,它得到锁。第二个pause\u my\u操作将简单地设置一个内部事件来标记计时器已取消,但这可能不会阻止pausetimeout继续,因为它已经被服务。因此,第二次暂停调用不会产生任何效果,它的计时器将被第一次暂停的超时调用取消

你知道我怎么解决这个问题吗


Tags: the方法selflock应用程序ifmydef
1条回答
网友
1楼 · 发布于 2024-10-01 17:33:47

您可以创建一个以pause_my_operation()递增,以pausetimeout()递减的变量。然后,pausetimeout()将只在变量减量后为0时执行其逻辑。使用此逻辑,只有最后的pausetimeot()将恢复代码

例如:

def pause_my_operation():
     with self._lock:
         self._counter += 1
         # check if there is already an existing timer, if present then cancel the timer and start a new timer
         # pause the operation

def pausetimeout():
    with self._lock:
        self._counter -= 1
        if self._counter == 0:
            # check if there is already an existing timer, if present then cancel it.
            # resume the operation

编辑

显然,这样做会产生另一个问题:如果取消计时器而不减少值,那么清除代码就不会触发。为了解决这个问题,如果可能的话,您永远不应该取消旧计时器,即:

def pause_my_operation():
     with self._lock:
         self._counter += 1
         # start a new timer
         # pause the operation

def pausetimeout():
    with self._lock:
        self._counter -= 1
        if self._counter == 0:
            # resume the operation

这应该不会影响性能,因为一次几乎总是只有一个计时器

相关问题 更多 >

    热门问题