使用python的全局变量和循环会增加线程的内存

2024-07-05 12:14:29 发布

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

基本上,我有一个基于GUI的程序(Tkinter),我使用多个线程来更新值和做其他事情。这样,我就有了一个全局变量,希望在线程之间共享,因为一个变量将更新不断变化的值(thread1),而另一个变量将在thread2的某些循环中使用相同的值来完成自己的任务。对于thread2,我希望它永远运行,不断地将此值检查为设置的<;40或>;40。我已经确定内存的增加来自thread2,因为注释thread out会使程序在没有显著内存增加的情况下运行。它与vlc对象无关,对我来说,它似乎是一个全局变量,或者它处于一个无限循环中。你知道吗

下面是thread2的简化代码和完整代码。我计划在rpi上运行这个程序,在2分钟内它将获得大约1GB的内存消耗。你知道吗

任何帮助都是非常感激的。谢谢!!你知道吗

(import vlc and others)
globalVar = 0.0

def Thread1():
    global globalVar
    #...modifies globalVar and GUI values

def Thread2():
    nowPlaying = vlc.MediaPlayer("song1.mp3")
    nowPlaying.play()
    changePlaying = vlc.MediaPlayer("song2.mp3")

    while True:
        extra = 0
        caseNum = random.randint(1,3)
        if caseNum == 1:
            eurobeat = vlc.MediaPlayer("song4.mp3")
        elif caseNum == 2:
            eurobeat = vlc.MediaPlayer("song5.mp3")
        elif caseNum == 3:
            eurobeat = vlc.MediaPlayer("song6.mp3")



        while globalVar >= 40:
            extra = extra + 1
            nowPlaying.set_pause(1)

            if (changePlaying.is_playing()) == 0:
                changePlaying.play()
                if extra > 2:
                    time.sleep(3)
                time.sleep(3)

            if globalVar < 40:
                nowPlaying.set_pause(0)
                changePlaying.stop()
            changePlaying.stop()

thread1 = Thread(target=Thread1)
thread1.setDaemon(True)
thread1.start()

thread2 = Thread(target=Thread2)
thread2.setDaemon(True)
thread2.start()

(tkinter)
root.mainloop()

Tags: 内存程序trueifextramp3vlcmediaplayer