<p>This is an example only. </p>
<div class="gmail_quote">On Mar 15, 2012 1:46 AM, "Andrew Svetlov" <<a href="mailto:andrew.svetlov@gmail.com">andrew.svetlov@gmail.com</a>> wrote:<br type="attribution"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
You still can get race condition:<br>
<br>
if b.add(a):<br>
# some thread removes a from b before do_c call...<br>
do_c()<br>
<br>
Explicit lock is still required for your case.<br>
<br>
On Wed, Mar 14, 2012 at 10:36 AM, Matt Joiner <<a href="mailto:anacrolix@gmail.com">anacrolix@gmail.com</a>> wrote:<br>
> set.add(x) could return True if x was added to the set, and False if x<br>
> was already in the set.<br>
><br>
> Adding an element that is already present often constitutes an error in my code.<br>
><br>
> As I understand, set.add is an atomic operation. Having set.add return<br>
> a boolean will also allow EAFP-style code with regard to handling<br>
> duplicates, the long winded form of which is currently:<br>
><br>
> if a not in b:<br>
> b.add(a) <-- race condition<br>
> do_c()<br>
><br>
> Which can be improved to:<br>
><br>
> if b.add(a):<br>
> do_c()<br>
><br>
> Advantages:<br>
> * Very common code pattern.<br>
> * More concise.<br>
> * Allows interpreter atomicity to be exploited, often removing the<br>
> need for additional locking.<br>
> * Faster because it avoids double contain check, and can avoid locking.<br>
> _______________________________________________<br>
> Python-ideas mailing list<br>
> <a href="mailto:Python-ideas@python.org">Python-ideas@python.org</a><br>
> <a href="http://mail.python.org/mailman/listinfo/python-ideas" target="_blank">http://mail.python.org/mailman/listinfo/python-ideas</a><br>
</blockquote></div>