python 3.2 global variable not updating when its in a thread

瘦欲@ 提交于 2019-12-24 11:44:44

问题


I'm making a program and I got into a problem. I have a thread running which has a while loop that checks if a global variable is equal to False, if its equal to True then exit the while loop. The problem is even if i update the global variable to True it still doesn't stop, it just continues on.

Code:

While loop:

while stopIt==False:
    print(stopIt) # Always prints out False, even when exit() is called
    # do things...

Stopper:

def exit():
    stopIt = True

stopIt variable defenition:

global stopIt
stopIt = False

回答1:


The global declaration must be inside the function where you modify the global variable:

def exit():
    global stopIt
    stopIt = True


来源:https://stackoverflow.com/questions/16742648/python-3-2-global-variable-not-updating-when-its-in-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!