python全局变量的修改 线程共享全局变量
程序员文章站
2024-02-16 08:56:04
...
箭头指向不变,而修改里面的值,则可不加global
如果箭头指向的方向变,则必须加global
至于哪些可变哪些不可变,要看具体的数据类型 数字,字符串、元组不可变,其它可变
num = 100
def test():
global num
num += 100
print(num)
test()
print(num)
import threading
import time
g_num = 100
def test1():
global g_num
g_num += 11
print("---------test1--- g_num =%d----" % g_num)
def test2():
print("---------test2--- g_num =%d----" % g_num)
def main():
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
time.sleep(1)
t2.start()
time.sleep(1)
print("----in main Thread g_num = %d" % g_num)
if __name__ == "__main__":
main()