首页 > 解决方案 > Python - 带有条件对象的评估顺序

问题描述

我试图了解 a 的condition object工作原理,并且从我编写的一个小型测试程序中得到了一些看似非常奇怪的行为。我添加了一堆打印语句来显示程序行的执行顺序。

alert()我在 a中调用一个函数thread,要求用户输入一个字母。如果该字母是“f”,那么这将触发条件并提醒程序该条件已满足。为了更容易可视化,程序中的打印语句是缩进的,而函数中的打印语句不是。

import threading
import time

def alert():
    while True:
        letter = input("Input a letter:\n")
        print("letter == f:",letter == 'f')
        if letter == 'f':
            print("Enter if true branch")
            with cond:
                print("Enter cond notify block")
                cond.notify()
                print("notified cond")
                return 1


cond = threading.Condition()

thread1 = threading.Thread(target=alert)
thread1.start()

with cond:
    print("     Enter cond wait block")
    cond.wait_for(alert)
    print("     Alert triggered")

print("     Program finished")

运行程序我得到以下结果:

     Enter cond wait block
Input a letter:
f
Input a letter:
letter == f: True
Enter if true branch
f
letter == f: True
Enter if true branch
Enter cond notify block
notified cond
     Alert triggered
     Program finished
Enter cond notify block
notified cond

输出显示程序进入条件块with cond并停在cond.wait.for(alert),等待通知。该alert()函数要求一个字母。我输入'f'。然后是令人惊讶的部分。在评估下一行(print()语句)之前,该alert()函数已完成整个while循环并正在请求另一个字母。这怎么可能?

即使alert()函数在while循环中一直运行(也许print()语句很慢),它也会命中return语句。一旦return被调用,为什么该alert()函数会通过while循环进行另一次迭代?

然后最后两行输出显示该alert()函数第二次运行条件通知块with cond。但这一次return语句起作用并结束了函数,因为它不再要求任何字母。

标签: pythonmultithreadingconditional-statements

解决方案


推荐阅读