如何在python3中跨线程使用另一个文件中的全局变量?

2024-07-05 12:13:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将python3代码分割成多个文件,因为我的项目代码太长了。但是,当我这样做的时候,我遇到了一个全局变量问题,涉及多个线程

下面是我的问题的简单描述:有三个py文件

config.py:

globalVar = 0

sub_thread.py:

import time
from config import globalVar

def sub_thread(e):
    global globalVar
        
    while True:
        globalVar = 200 
        print("globalVar from the thread is:", globalVar)
            
        time.sleep(0.5)

main.py:

import time
import threading
from config import globalVar
from sub_thread import sub_thread
    
if __name__ == '__main__':
    
    print("Default value of globalVar:", globalVar)
        
    e = threading.Event()
    thread_0 = threading.Thread(target=sub_thread, args=(e, ))
    thread_0.daemon = True

    thread_0.start()
    e.set()

    while(True):
        print("globalVar from the main is:", globalVar)
        time.sleep(0.5)

结果如下:

~$ python3 main.py

Default value of globalVar: 0
globalVar from the thread is: 200
globalVar from the main is: 0
globalVar from the thread is: 200
globalVar from the main is: 0
globalVar from the thread is: 200
globalVar from the main is: 0
globalVar from the thread is: 200

为什么来自线程的更改不会影响主线程,即使它是一个全局变量?

为什么会发生这种情况,我该如何解决? 除了将三个文件合并成一个文件,还有其他答案吗


Tags: 文件thefrompyimportconfigtruetime