thread safe to lock on key,val pairs on a dict instead of entire dict?

birdsong david.birdsong at gmail.com
Wed Feb 25 21:39:30 EST 2009


Dictionaries just store references to objects, right?  So is it thread
safe to lock a specific key/val pair on a dictionary and modify its
val and release the lock?

example snippet:
# assuming d_lock  was initialized long ago in a thread-safe manner
d_lock.acquire()
d = {}
d[1] = (threading.Lock(), [])
d_lock.release()

# test key level locking
for key, data in d.items():
  row_lock, rows = data
  row_lock.acquire()
  rows.append(1)
  row_lock.release()

Of course, I'll have to lock the entire dict when adding keys that
dont exist, but further calls and acquire the key specific lock before
doing any write operations.



More information about the Python-list mailing list