为什么while循环中的else:'部分没有被调用?

2024-04-19 00:12:12 发布

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

我试图用事件对象控制python代码中的两个线程。在一个线程中,我等待另一个线程将事件设置为True并在它保持为True时执行,否则,执行其他操作。我的问题是循环的“else”部分永远不会被调用。知道为什么吗?事先非常感谢。你知道吗

我试过把while语句改成if语句,但没有成功。我真的不知道为什么这样不行。你知道吗

def send_thread(self):
        rospy.loginfo('set')
        self.event.set()
        for cmd in sequence:
            Do something
        rospy.sleep(2)
        rospy.loginfo('saving command in full')
        self.U_full.append(self.U_single)
        self.event.clear()
def receive_thread(self,msg):
        while self.event.wait() == True:
           Do something
        else:
           Do something else

预期的结果是接收线程的'while'部分一直运行,直到事件在发送线程中被清除,然后执行'else'部分。你知道吗


Tags: selfeventtruedef事件语句线程do
1条回答
网友
1楼 · 发布于 2024-04-19 00:12:12

您正在等待一个没有超时的事件,因此self.event.wait()总是True。从^{} documentation

This method returns true if and only if the internal flag has been set to true, either before the wait call or after the wait starts, so it will always return True except if a timeout is given and the operation times out.

我的。因为它总是返回true,所以您永远不会看到执行else:套件。你知道吗

很明显,如果不使用超时,while循环将永远不会退出,因为没有超时,event.wait()只会在事件标志为true时返回。用self.event.clear()清除标志会将标志设置为False,因此event.wait()不会返回。你知道吗

使用超时:

while self.event.wait(0.1):
    # do something while the event is still set
else:
    # the event has been cleared and the timeout has been reached!
    # This block can be skipped if the while block uses 'break'

注:测试self.event.wait()就足够了。== True部分是完全冗余的。另外,只有在while循环中使用break来显式跳过else块时,while test: ... else: ...设置才有意义。如果您没有在while块中使用break,那么您最好删除else:,然后无条件地运行该块中缩进的代码。你知道吗

或者,测试^{}

while event.is_set():
    # do something while the event is still set
else:
    # the event has been cleared and 'break' was not used

或者,反转事件,在开始时清除它,并仅在完成时设置事件:

def send_thread(self):
    rospy.loginfo('set')
    self.event.clear()
    for cmd in sequence:
        Do something
    rospy.sleep(2)
    rospy.loginfo('saving command in full')
    self.U_full.append(self.U_single)
    self.event.set()

然后等待事件设置:

if self.event.wait():
    # blocks until the event has been set by the other thread.

或者如果你想在那之前做一些事情,在你的while循环中使用not self.event.wait(0.1)或者简单的not self.event.is_set()。你知道吗

相关问题 更多 >