线程类中的全局变量不升级

2024-04-19 18:51:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经相信他们的答案了。在下面的例子中,有人能解释为什么线程没有发现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

Tags: 答案importselftruetimeinitdefscript
1条回答
网友
1楼 · 发布于 2024-04-19 18:51:59

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

以下是我的代码版本:

^{pr2}$

你实际上有一个小错误:

t = ThreadClass().start()

start()方法返回None,因此t将是{}。您需要分别实例化线程,然后启动它。另外,我会显式地等待线程加入:

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'

相关问题 更多 >