繁体   English   中英

条件变量以在完成特定任务后暂停线程(在Python中)

[英]Condition variable to pause a thread after finishing a particular task (in Python)

我正在为一个程序实现GUI,该程序针对总线路由问题构建和修改大图。

我想有一个Play按钮,应该开始模拟(创建一个新线程simThread,该线程执行Simulate()方法,这几乎是一个无限循环,一遍又一遍地调用方法ModifyGraph())。

我还需要一个“暂停”按钮,当按下该按钮时会导致simThread等待,但要等到它完成了对ModifyGraph()的当前调用后才能等待。 这是因为在ModifyGraph()期间,图形通常处于不应绘制的状态。 当我再次按Play时,理想情况下simThread应该继续原样。

我对于一般的线程尤其是Python还是比较陌生的,但是我有一种感觉,条件变量是要走的路。 有人知道该怎么做吗?

如果您的simThread看起来像这样:

class simThread(threading.Thread):
    def run(self):
        while True:
            modifyGraph()

您可以像这样引入要取消暂停的事件:

class simThread(threading.Thread):
    def __init__(self):
        self.unpaused = threading.Event()
        self.unpaused.set()
        threading.Thread.__init__(self)

    def run(self):
        while True:
            modifyGraph()
            unpaused.wait()

您将使用以下功能:

thread = simThread()
thread.start()
thread.unpaused.clear()
[...]
thread.unpaused.set()

如果您认为一个名为unpaused的事件有点尴尬,那么您还可以将最初设置为False的另一个布尔变量pause 在线程中,您将检查它是否为True ,然后等待取消暂停事件。 所以像这样:

class simThread(threading.Thread):
    def __init__(self):
        self.pause = False
        self.unpause = threading.Event()
        threading.Thread.__init__(self)

    def run(self):
        while True:
            modifyGraph()
            if self.pause:
                unpause.wait()

    def pause(self):
        self.unpause.clear()
        self.pause = True

    def unpause(self):
        self.pause = False
        self.unpause.set()

thread = simThread()
thread.start()
thread.pause()
thread.unpause()

之所以要使用一个事件,而不是仅仅对self.pause进行另一个while循环旋转,是为了避免浪费CPU周期。

暂无
暂无

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

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