简体   繁体   中英

python global variable is not saved global

NexusConnectedClients = []

class Thread1(NexusCore.Thread):
    def Run():
        global NexusConnectedClients
        if(IncomingCommand == "ADDCLIENT"):
            NewClientOBJ = [
                LastCID,
                ClientType,
                ClientADDR,
                ClientObject,
                Args[1],
                Args[2],
                '{"events":[]}'
            ]
            NexusConnectedClients.append(NewClientOBJ)
        elif(IncomingCommand == "LISTCLIENTS"):
            SendResponse(NexusConnectedClients)

When i add an client, it is ok. When i read the NexusConnectedClients variable, it is add to the list. But when i run the LISTCLIENTS function, the list is empty. What is wrong?

I Simplified the code a bit. all the variables are set and all other global variables work as they should.

EDIT I found the mistake, nothing wrong with this code but another function deleted the element from the NexusConnectedClients array

You don't need to declare NexusConnectedClients as global since it is visible in the run method. A variable must be declared global when you want to (re)bind a name in the global scope. When a variable is modifiable, and lists are, just modify it.

Instead what you have to do is to regulate the access to the NexusConnectedClients . You are modifying a shared variable inside a thread, maybe more than one. Use a lock. Said that, I think nothing more could be said in a such small snippet.

Solved the problem. Didn't remove an line of code from previous testing. That line resetted the array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM