Python中线程未更新全局变量

1 投票
1 回答
31 浏览
提问于 2025-04-13 12:36

我有一个线程,每小时检查一次时间,并不断更新一个全局变量。但是不知道为什么,使用全局变量的声明并没有起作用,导致这个全局变量即使被线程更新了,值还是保持不变。请看我的代码:

paymentDate = "2024-03-22"
currentDate = ""

#Function that is in charge of validate the date
def isSystemValidDateReached():
    global currentDate

    try:
        if currentDate == "":
            currentDate = str(urlopen('http://just-the-time.appspot.com').read().strip().decode('utf-8'))

        if paymentDate < currentDate:
            return True
        else:
            return False
    except Exception as e:
        log.appendToLog("Error", "critical")


#function that is being used in a thread
def getTimeFromInternet(timeSleep=3600):
global currentDate
while True:
    try:
        time.sleep(timeSleep)            
        currentDate = str(urlopen('http://just-the-time.appspot.com').read().strip().decode('utf-8'))
        print("new current date {}".format(currentDate)) 
    except Exception as e:
        log.appendToLog("Error: {}".format(e), "critical")

这是主脚本中的一部分,这个函数在一个循环中每隔一段时间就会被检查:

if isSystemValidDateReached():
    exit()

# get time every hour
getDateFunctionThread = multiprocessing.Process(target=getTimeFromInternet)
getDateFunctionThread.start()

我遇到的问题是,我在getTimeFromInternet函数里设置了一个断点,它会更新currentDate,但是当调用isSystemValidDateReached()函数时,我看到的还是这段代码里老旧的值:

if currentDate == "":
        currentDate = str(urlopen('http://just-the-time.appspot.com').read().strip().decode('utf-8'))

我需要做什么改变,才能让这个变量在我的线程函数中每小时更新一次呢?

1 个回答

0

正如chepner所说,问题的解决方法是因为我使用了多进程而不是线程,下面是相关代码:

getDateFunctionThread = Thread(target=getTimeFromInternet)
getDateFunctionThread.start()

撰写回答