线程类中的全局变量不会更新

时间:2015-12-01 10:52:47

标签: python

A couple questions就此问题,但我相信我已经在遵循他们的解决方案了。在下面的示例中,有人可以说为什么线程没有发现boolean更新为True?我在全球范围内定义了它。

import threading
import time

boolean = False

class ThreadClass(threading.Thread):
  def __init__(self):
    global boolean
    super(ThreadClass, self).__init__()
  def run(self):
    global boolean
    for i in range(6):
      print str(i)
      time.sleep(1)

t = ThreadClass().start()
time.sleep(3)
boolean = True
print 'end script'
0
1
2
end script
3
4
5

1 个答案:

答案 0 :(得分:2)

print str(i)更改为print str(i), boolean,您会发现它确实发生了变化:

:: python so-python-thread.py
0 False
1 False
2 False
end script
3 True
4 True
5 True

这是我的代码版本:

import threading
import time


boolean = False


class ThreadClass(threading.Thread):
    def __init__(self):
        super(ThreadClass, self).__init__()

    def run(self):
        global boolean
        for i in range(6):
            print str(i), boolean
            time.sleep(1)


t = ThreadClass().start()
time.sleep(3)
boolean = True
print 'end script'

你确实有一个小错误:

t = ThreadClass().start()

start()方法返回None,因此t将为None。您需要单独实例化线程,然后启动它。另外,我明确地等待线程加入:

import threading
import time


boolean = False


class ThreadClass(threading.Thread):
    def __init__(self):
        super(ThreadClass, self).__init__()

    def run(self):
        global boolean
        for i in range(6):
            print str(i), boolean
            time.sleep(1)


t = ThreadClass()
t.start()

time.sleep(3)
boolean = True

t.join()
print 'end script'