Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It looks to me like this is an attempt at optimisation gone slightly wrong. I <em>suspect</em> it's trying for "TATAS" - "Test-and-test-and-set", where it doesn't even try to do the TestAndSet if it can see the lock is already taken.</p> <p>In a <a href="http://www.bluebytesoftware.com/blog/CommentView,guid,72aaa68e-4cbd-41db-a7ce-ddc64411eafa.aspx" rel="noreferrer">post about spin locks for .NET</a>, Joe Duffy writes this TATAS code as:</p> <pre><code>class SpinLock { private volatile int m_taken; public void Enter() { while (true) { if (m_taken == 0 &amp;&amp; Interlocked.Exchange(ref m_taken, 1) == 0) break; } } public void Exit() { m_taken = 0; } } </code></pre> <p>(Note that Joe is using 1 to mean locked and 0 to mean unlocked, unlike the code project sample - either is fine, just don't get confused between the two!)</p> <p>Note that here the call to Interlocked.Exchange <em>is conditional on <code>m_taken</code> being 0</em>. This reduces contention - the relatively expensive (I guess) test-and-set operation is avoided there it's unnecessary. I <em>suspect</em> that's what the author was aiming at, but didn't quite get it right.</p> <p>This is also mentioned in the <a href="http://en.wikipedia.org/wiki/Spin_locking" rel="noreferrer">Wikipedia article about spinlocks</a> under "significant optimisations":</p> <blockquote> <p>To reduce inter-CPU bus traffic, when the lock is not acquired, the code should loop reading without trying to write anything, until it reads a changed value. Because of MESI caching protocols, this causes the cache line for the lock to become "Shared"; then there is remarkably no bus traffic while a CPU is waiting for the lock. This optimization is effective on all CPU architectures that have a cache per CPU, because MESI is so ubiquitous.</p> </blockquote> <p>That "loop reading" is exactly what the while loop does - until it sees <code>m_taken</code> change, it only reads. When it sees the change (i.e. when the lock is released) it has another go at locking.</p> <p>Of course it's very possible that I'm missing something important - issues like this are very subtle.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload