Suppose I have some dictionary in python and I want to be able to guarantee a value for a given key is only set once.
I know I can do this by checking has_key(newkey)
, followed by dict[newkey]=value
.
This works fine for a single-threaded application:
d = { 1:'spam', 2:'eggs' }
def add_entry( key, val ):
if not d.has_key(key):
d[key] = val
else:
raise Exception('Nice try, but value with key '%s' already exists' %str(key))
# Succeeds
add_entry( 3, 'ham' )
# Fails with exception
add_entry( 2, 'cheese' )
However, I want to achieve this same behavior from a multi-threaded application.
What's a thread safe impl of add_entry
above? Is there a builtin method / data structure I'm missing that just does this? Or do I need to use an explicit lock?