【问题标题】:How to access global variables from a thread in Python如何从 Python 中的线程访问全局变量
【发布时间】:2016-08-10 08:44:06
【问题描述】:

考虑以下代码:

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。为什么会这样,我怎样才能正确访问它?

【问题讨论】:

    标签: python multithreading thread-safety


    【解决方案1】:

    您需要在第一个定义时将 number 设为全局,如下所示:

    def main():
        global number
        number = 5
    
    ...etc...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多