In article <50fa1bf1$0$30003$c3e8da3$54964...@news.astraweb.com>, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote:
> I wish to add a key to a dict only if it doesn't already exist, but do it > in a thread-safe manner. > > The naive code is: > > if key not in dict: > dict[key] = value > > > but of course there is a race condition there: it is possible that > another thread may have added the same key between the check and the > store. > > How can I add a key in a thread-safe manner? You want something along the lines of: from threading import Lock lock = Lock() [...] lock.acquire() if key not in dict: dict[key] = value lock.release() You probably want to wrap that up in a context manager to ensure the lock is released if you get an exception. You don't want your entire program to hang just because somebody handed you a key which wasn't hashable, for example. -- http://mail.python.org/mailman/listinfo/python-list