简体   繁体   中英

Python thread doesn't change global variable inside a function

The most basic form of something I want to code is the code as follows:

import threading

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

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

What I want to do is to append "8" to a global variable called arr But this doesn't happen, and print(arr) gives this output:

[]

However, if I use this code, everything works fine:

import threading

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

test("8")
print(arr)

The problem seems to be with thread, so how can I use thread and also change the value of a global variable inside the function test ?

You also have to start the thread to actually run the function 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM