python 3.2全局变量在线程中时不更新 [英] python 3.2 global variable not updating when its in a thread

查看:558
本文介绍了python 3.2全局变量在线程中时不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写程序,但遇到了问题. 我正在运行一个线程,该线程具有while循环,该循环检查全局变量是否等于False,如果其等于True,则退出while循环. 问题是,即使我将全局变量更新为True,它仍然不会停止,只会继续运行.

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.

代码:

循环时

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

停止器:

def exit():
    stopIt = True

stopIt变量定义:

stopIt variable defenition:

global stopIt
stopIt = False

推荐答案

global声明必须位于修改全局变量的函数中:

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

def exit():
    global stopIt
    stopIt = True

这篇关于python 3.2全局变量在线程中时不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆