gpt4 book ai didi

python - 我想停止 python 中的平方函数线程,但它不起作用?

转载 作者:行者123 更新时间:2023-12-01 01:00:04 24 4
gpt4 key购买 nike

我创建了一个平方函数,当我输入“start”时,它将从 1,2...开始平方,当我输入“stop”时结束平方。当我输入“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 中定义和使用的 flag 变量是本地的,与线程使用的变量无关,因此线程永远不会通过其更改通知(因此较新的人知道何时该停止)。
解决方法很简单,在 main 中将变量设置为全局变量(与 square 中已完成的方式相同):

global flag

square 函数也可以简化,而不是:

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 .

关于python - 我想停止 python 中的平方函数线程,但它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55879822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com