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

birdsong david.birdsong at
Thu Feb 26 03:39:30 CET 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 = {}
d[1] = (threading.Lock(), [])

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

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