Python线程不会更改函数内部的全局变量

时间:2018-09-26 08:27:40

标签: python multithreading global-variables

我想编写的最基本形式的代码如下:

import threading

arr = []
def test(id):
    global arr
    arr.append(id)

threading.Thread(target=test, args="8")
print(arr)

我想要做的是将“ 8”附加到名为 arr 的全局变量中,但这不会发生,并且 print(arr)给出以下输出:

[]

但是,如果我使用此代码,则一切正常:

import threading

arr = []
def test(id):
    global arr
    arr.append(id)

test("8")
print(arr)

问题似乎出在线程上,所以我该如何使用线程并在函数 test 中更改全局变量的值?

1 个答案:

答案 0 :(得分:5)

您还必须启动线程才能实际运行功能test

import threading

arr = []
def test(id):
    global arr
    arr.append(id)

t = threading.Thread(target=test, args="8")
t.start()
t.join()
print(arr)
相关问题