在python信号量P操作源码中,有一段while-else格式的代码:while self._value == 0: …
def acquire(self, blocking=True, timeout=None):
if not blocking and timeout is not None:
raise ValueError("can't specify timeout for non-blocking acquire")
rc = False
endtime = None
with self._cond:
while self._value == 0:
if not blocking:
break
if timeout is not None:
if endtime is None:
endtime = _time() + timeout
else:
timeout = endtime - _time()
if timeout <= 0:
break
self._cond.wait(timeout)
else:
self._value -= 1
rc = True
return rc
自行举了几个例子测试逻辑:
1、不符合循环条件,执行else
count = 6
while count <= 5:
count += 1
if count == 4:
continue
print("Loop", count)
else:
print("while正常执行完或不符合while循环条件")
print("-----out of while loop ------")
结果:
while正常执行完或不符合while循环条件 -----out of while loop ------
2、循环中途break,不执行else
count = 0
while count <= 5:
count += 1
if count == 4:
break
print("Loop", count)
else:
print("while正常执行完或不符合while循环条件")
print("-----out of while loop ------")
....
结果:
Loop 1 Loop 2 Loop 3 -----out of while loop ------
3、while正常执行完毕,执行else
count = 0
while count <= 5:
count += 1
if count == 4:
continue
print("Loop", count)
else:
print("while正常执行完或不符合while循环条件")
print("-----out of while loop ------")
....
结果:
Loop 1 Loop 2 Loop 3 Loop 5 Loop 6 while正常执行完或不符合while循环条件 -----out of while loop ------
|