首页 > 解决方案 > 为什么全局变量在线程中有不同的值?

问题描述

A 中的全局变量 g_tmp 发生变化。在线程 B 中输出 g_tmp 时,它保持不变。

from time import sleep, time
from multiprocessing import Process, current_process

g_tmp=[0,0]

def A():
    while True:
        sleep(20)
        global g_tmp
        print(g_tmp)
        print(str(g_tmp[0]+g_tmp[1]))

def B():
    global g_tmp
    while True:
        sleep(2)
        g_tmp[0]+=1
        print(g_tmp)

def main(): 
    threadA = Process(target=A, name='A')
    threadA.start()
    threadB = Process(target=B, name='B')
    threadB.start()  
    threadB.join()

if __name__ == "__main__":
    main()

如何对所有线程中可见的全局变量进行更改?比如前20秒后显示[10.0] 10?

标签: pythonpython-3.xmultithreadingmultiprocessing

解决方案


推荐阅读