我已经创建了一个方形函数,它将从1,2开始平方...当我输入“开始”并在我输入“停止”时结束平方。当我输入“start”时,我开始每隔2秒获得一个数字方块,但是当我输入“stop”时,线程没有停止。我使用变量'flag'来停止该功能。这是代码。
import threading
import time
flag=False
def square():
i=1;
global flag
while(True):
print(i*i,"\n")
time.sleep(2)
i=i+1
if(flag):
break
def main():
while(True):
x=input("Enter start/stop")
if(x=="start"):
flag=False
p = threading.Thread(target=square)
p.start()
if(x=="stop"):
flag=True
p.join()
main()
问题是在main中定义和使用的标志变量是本地的,并且与线程使用的标志变量无关,因此线程从未被其更改通知(因此更新的人知道何时停止)。 修复很简单,使变量全局变为主要(与已在广场中完成的方式相同):
global flag
方形函数也可以简化,而不是:
while True:
# The other instructions
if(flag):
break
你可以这样做:
while not flag:
# The other instructions
作为一个注释,线程之间还有其他同步方式,例如:
threading.Event
p = threading.Thread(target=square, daemon=True)
,即使一般不推荐),这意味着它将在main到达终点时突然停止有关更多信息,请查看[Python 3.docs]: threading - Thread-based parallelism。