0
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 ??

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot for your answer. I have already applied the locks but the values is persisting.
sounds more like a design issue then going on somewhere else in your code. if you're getting one value in the cmdid dict but you expected another, then it all depends on when and where you are calling setCmdId(). Either the value you expect to get isn't being written (you're not calling setCmdId() / the thread isn't executing) or you're accidentally calling setCmdId() twice in the same thread.
I got the issue. I needed to make the contextfilter class threadsafe and it worked !!thanks a lot for your help and patience :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.