0

I've a question about concurrent programming in python.

Let's say I have two threads, thread-R and thread-W. Thread-R just reads a variable and Thread-W updates the this variable regularly. Further it is only required that Thread-R does not crash for some reason, and that thread-R just gets the value either stored before the update of thread-W or after.

So,acutally a quite easy setting. However, I'm asking myself if for some reason thread-R might get a wrong value from the variable.

So my question therefore: Do I need to lock the variable when thread-W updates the value such that thread-R is blocked until thread-W has finished updating the variable?

UPDATE: Ok, basically. I have on object like

class MyObject(object):

    def __init__(self):
        self.A = "A String"

And those object are stored in a dict like:

{key1 : myobject_instance_1, key2 : myobject_instance_2, ... }

So, thread-W would update instance variable "A" each time but not the dictionary itself.

toom
  • 12,864
  • 27
  • 89
  • 128
  • 2
    It depends on the variable's object and how the updates happen. If it's simple assignment, I wouldn't worry. But if W is updating a dict, I'd protect it with a lock. Any time an operation takes more than 1 byte code, it can get interrupted. – tdelaney Dec 12 '14 at 17:48
  • This is pertinent if you're using CPython: http://stackoverflow.com/q/1294382/10077 – Fred Larson Dec 12 '14 at 17:48
  • Are you optimistic or pessimistic? :) – frostbite Dec 12 '14 at 17:48
  • according to this: http://effbot.org/zone/thread-synchronization.htm fetching an item from a dictionary and in place dictionary edits are atomic ops. – frostbite Dec 12 '14 at 18:06

0 Answers0