DoNNie_DarkO
DoNNie_DarkO

Reputation: 367

changing global variables in threads in python

test_var="TEST"

class exLogging(logging.Logger):
  cmdidDict[threading.currentThread()]="default"
  def __init__(self, name):
    logging.Logger.__init__(self, name)
    cmdidDict[threading.currentThread()]="default"
    return
  def setCmdId(self, newCmdId): #threadsafe sync
    for k,v in cmdidDict.items():
      cmdidDict[threading.currentThread()]=newCmdId
      test_var=newCmdId
      obj=ContextFilter(test_var)          #ContextFilter is another class
      self.addFilter(obj)
      self.info("in setcmdid")

I want the setCmdId function in the class to be threadsafe as this function individually will be called from various threads. By threadsafe I mean that I want setCmdId function to set values of CMDID differently in each different thread and once the thread is over CMDID should attain its global value. CMDID and cmdidDict[] are global variables. The problem is that CMDID values persist. Can anyone point me in the right direction ??

Upvotes: 0

Views: 693

Answers (1)

cronburg
cronburg

Reputation: 891

Check out this answer: https://stackoverflow.com/a/4542436/1542000

The only sure-fire way to guarantee thread-safety is to use some sort of locking mechanism inside your function:

lock = threading.Lock()
lock.acquire()
...
lock.release()

This will make it so that no two threads will be accessing the dictionary at the same time and thus eliminate race conditions.

It's hard to tell what's going on in your setCmdId function, especially since it appears the for loop is doing nothing more than repeating the commands len(cmdidDict.items()) times. If we knew better what you're trying to accomplish we might be able to come up with a better solution than just slapping a lock onto the function.

Upvotes: 2

Related Questions