全局变量跨线程不更新

时间:2014-02-07 19:06:22

标签: python multithreading

我已经将下面的内容作为我所见所见的演示。

基本上,在keydown上然后Z应该设置为2并且show_thread中的print循环应该输出这个新值但是即使我按下键,输出仍然只是说“Z是1”

根据我的检查,似乎Z在L下没有更新:但是我无法理解为什么。

我也试过加入

delay(1000)
Z = 999

在线程创建之下,然后输出显示“Z为1”10秒然后说(并且保持说)“Z是999”

import time
import thread

def input_thread(L):
    derp = raw_input()
    L.append(derp)

def show_thread(foo):
    while 1:
        print "Z is " + `Z`
        print "\n"
        time.sleep(2)

def main():
    global Z
    L = []
    thread.start_new_thread(input_thread, (L,))
    thread.start_new_thread(show_thread, (1,))

    while 1:
        if L:
            Z = 2
            print L[0]
            print "\n"

Z = 1
main()

2 个答案:

答案 0 :(得分:0)

main中,Z是一个局部变量,不会更改全局变量。您似乎通过将其包含在帖子的标题中来了解全局概念,但您并未在代码中使用它。将global Z添加到main()

的顶部
def main():
    global Z   # <--- here
    L = []
    thread.start_new_thread(input_thread, (L,))
    thread.start_new_thread(show_thread, (1,))

    while 1:
        if L:
            Z = 2
            print L[0]
            print "\n"

或重构代码以使用class,因此您有self.Z或类似的

答案 1 :(得分:0)

添加到了hhlester的答案。您需要删除print函数中的main语句。

import time
import thread

def input_thread(L):
    derp = raw_input()
    L.append(derp)

def show_thread(foo):
    while 1:
        print "Z is " + repr(Z) # Do not use backtick(`). Use `repr`
        print "\n"
        time.sleep(2)

def main():
    global Z  # declare `Z` as global
    L = []
    thread.start_new_thread(input_thread, (L,))
    thread.start_new_thread(show_thread, (1,))

    while 1:
        if L:
            Z = 2
            # Remove following print statements,
            #   otherwise it will cover the terminal with empty lines.
            #print L[0]  <---------
            #print "\n"  <---------

Z = 1
main()