如何从Python中的线程访问全局变量

时间:2016-08-10 08:44:07

标签: python multithreading thread-safety

请考虑以下代码:

from threading import Thread 

def main():
    number = 5

    class my_thread(Thread):
        def __init__(self, range):
            Thread.__init__(self)
            self.range = range

        def run(self):
            global number
            for i in self.range:
                number += 1

    t1 = my_thread(range(4))
    t1.start()
    t1.join()
    print number

main()

此程序的输出是

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Tools\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Dev\Workspace\Hello World\Hello.py", line 14, in run
    number += 1
NameError: global name 'number' is not defined

5

显然,my_thread无法访问number。为什么这样,我怎样才能正确访问它?

1 个答案:

答案 0 :(得分:2)

你需要让number成为第一个定义的全局,如下所示:

def main():
    global number
    number = 5

...etc...