Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python线程没有';t更改函数中的全局变量_Python_Multithreading_Global Variables - Fatal编程技术网

Python线程没有';t更改函数中的全局变量

Python线程没有';t更改函数中的全局变量,python,multithreading,global-variables,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

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

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)

问题似乎出在线程上,因此如何使用线程并在函数测试中更改全局变量的值?

您还必须启动线程才能实际运行函数
测试

import threading

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

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

您还必须启动线程才能实际运行函数
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)