On Friday, January 18, 2013, Steven D'Aprano  wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">I wish to add a key to a dict only if it doesn't already exist, but do it<br>

in a thread-safe manner.<br>
<br>
The naive code is:<br>
<br>
if key not in dict:<br>
    dict[key] = value<br>
<br>
<br>
but of course there is a race condition there: it is possible that</blockquote><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
another thread may have added the same key between the check and the<br>
store.<br>
<br>
How can I add a key in a thread-safe manner?<br>
</blockquote><div><br></div><div>I'm not entirely sure, but have you investigated dict.setdefault() ?<span></span></div><br><br>-- <br>Cheers,<br>Chris<br>--<br><a href="http://rebertia.com" target="_blank">http://rebertia.com</a><br>