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

问题描述 投票:1回答:1

我已经创建了一个方形函数,它将从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()
python multithreading multitasking
1个回答
2
投票

问题是在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

© www.soinside.com 2019 - 2024. All rights reserved.