Karolizzz
Karolizzz

Reputation: 119

Variable in Thread class not showing correct output (Python)

I have a class showAllThreads that monitors all the existing threads in the script (music player)

class showAllThreads(threading.Thread):

    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        self.daemon = True
        self.start()

    #Shows whether the playing music is in queue, initially false
    musicQueue = False

    def run(self):
        while True:
            allThreads = threading.enumerate()
            for i in allThreads:
                if i.name == "PlayMusic" and i.queue == True:
                    musicQueue = True
                    print("Playlist is on")
                elif i.name == "PlayMusic" and i.queue == False:
                    musicQueue = False
                    print("Playlist is off")
                else:
                    musicQueue = False
            time.sleep(2)

When I try to access musicQueue from the mainthread by allThreads.musicQueue where allThreads = showAllThreads()it always gives me value False, even though the while loop executes musicQueue = True. I know that the playlist is on, because the print command excecutes successfully.

Upvotes: 0

Views: 35

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

You define "musicQueue" in two places: first at the class-level (which makes it a class attribute - an attribute that is shared between all instances of the class), then as a local variable in the run() method. These are two totally distinct names, so you can't expect assigning to the local variable to change the class-level one in any way.

I assume you're new to Python and didn't take time to learn how it's object model works and how it differs from most mainstream OOPLs. You really should if you hope to enjoy coding in Python...

What you want here is obviously to make musicQueue an instance variable and assign to it within run():

class ShowAllThreads(threading.Thread):

    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        self.daemon = True
        # create an instance variable
        self.musicQueue = False
        self.start()

    def run(self):
        while True:
            allThreads = threading.enumerate()
            for i in allThreads:
                if i.name == "PlayMusic" and i.queue == True:
                    # rebind the instance variable
                    self.musicQueue = True
                    print("Playlist is on")

                elif i.name == "PlayMusic" and i.queue == False:
                    self.musicQueue = False
                    print("Playlist is off")

                else:
                    self.musicQueue = False
            time.sleep(2)

Upvotes: 1

Related Questions