<div>That's what I was guessing. But then I thought maybe there might be some magic that either inserted a lock around the block of instructions from the first read to the last write, or else that detected these primatives and emitted a warning. Not that I'm suggesting that approach, as a general solution is probably impractical / full of landmines. And I guess getting lock free systems right is normally considered an "experts only" kind of thing, except maybe the one-pointer versions like linked list.</div>
<div> </div>
<div>Kevin<br></div>
<div> </div>
<div>On Tue, Jan 5, 2010 at 1:21 PM, Sean Kelly <span dir="ltr"><<a href="mailto:sean@invisibleduck.org">sean@invisibleduck.org</a>></span> wrote:</div>
<div class="gmail_quote">
<blockquote class="gmail_quote" style="PADDING-LEFT: 1ex; MARGIN: 0px 0px 0px 0.8ex; BORDER-LEFT: #ccc 1px solid">
<div>
<div></div>
<div class="h5">On Jan 5, 2010, at 10:14 AM, Kevin Bealer wrote:<br><br>> On Mon, Jan 4, 2010 at 6:58 PM, Andrei Alexandrescu <<a href="mailto:andrei@erdani.com">andrei@erdani.com</a>> wrote:<br>><br>> shared int x;<br>
> ...<br>> ++x;<br>><br>> The putative user notices that that doesn't work, so she's like, meh, I'll do this then:<br>><br>> int y = x;<br>> ++y;<br>> x = y;<br>><br>> And the user remains with this impression that the D compiler is a bit dumb. Of course that doesn't avoid the race condition though. If the user would have to call atomicIncrement(x) that would be clearly an improvement, but even this would be an improvement:<br>
><br>> int y = sharedRead(x);<br>> ++y;<br>> sharedWrite(y, x);<br>><br>> When writing such code the user inevitably hits on the documentation for the two intrinsics, which clearly define their guarantees: only the sequence of sharedRead and sharedWrite is preserved. At that point, inspecting the code and understanding how it works is improved.<br>
><br>> ...<br>> Andrei<br>><br>> Just to clarify, this is still broken, right? I mean that if two users are calling a method that does this,<br>> the value of x will only get incremented once if their calls to sharedRead/sharedWrite are interleaved?<br>
<br></div></div>Yes. You either need to call a special hardware instruction (LOCK INC on x86) or use a CAS loop:<br><br>void increment( ref shared int x )<br>{<br> int t;<br> do {<br> t = atomicLoad( x );<br> } while( !atomicStoreIf( x, t + 1, t ) ); // atomicStoreIf is a CAS<br>
<div>
<div></div>
<div class="h5">}<br><br>_______________________________________________<br>dmd-concurrency mailing list<br><a href="mailto:dmd-concurrency@puremagic.com">dmd-concurrency@puremagic.com</a><br><a href="http://lists.puremagic.com/mailman/listinfo/dmd-concurrency" target="_blank">http://lists.puremagic.com/mailman/listinfo/dmd-concurrency</a><br>
</div></div></blockquote></div><br>