Note that there are some explanatory texts on larger screens.

plurals
  1. POIntel Inspector reports a data race in my spinlock implementation
    text
    copied!<p>I made a very simple spinlock using the Interlocked functions in Windows and tested it on a dual-core CPU (two threads that increment a variable); </p> <p>The program seems to work OK (it gives the same result every time, which is not the case when no synchronization is used), but <em>Intel Parallel Inspector</em> says that there is a race condition at <em>value += j</em> (see the code below). The warning disappears when using Critical Sections instead of my SpinLock. </p> <p>Is my implementation of SpinLock correct or not ? It's really strange, because all the used operations are atomic and have the proper memory barriers and it shouldn't lead to race conditions.</p> <pre><code>class SpinLock { int *lockValue; SpinLock(int *value) : lockValue(value) { } void Lock() { while(InterlockedCompareExchange((volatile LONG*)lockValue, 1, 0) != 0) { WaitABit(); } } void Unlock() { InterlockedExchange((volatile LONG*)lockValue, 0); } }; </code></pre> <p>The test program: </p> <pre><code>static const int THREADS = 2; HANDLE completedEvents[THREADS]; int value = 0; int lock = 0; // Global. DWORD WINAPI TestThread(void *param) { HANDLE completed = (HANDLE)param; SpinLock testLock(&amp;lock); for(int i = 0;i &lt; 1000*20; i++) { for(int j = 0;j &lt; 10*10; j++) { // Add something to the variable. testLock.Lock(); value += j; testLock.Unlock(); } } SetEvent(completed); } int main() { for(int i = 0; i &lt; THREADS; i++) { completedEvents[i] = CreateEvent(NULL, true, false, NULL); } for(int i = 0; i &lt; THREADS; i++) { DWORD id; CreateThread(NULL, 0, TestThread, completedEvents[i], 0, &amp;id); } WaitForMultipleObjects(THREADS, completedEvents, true, INFINITE); cout&lt;&lt;value; } </code></pre>
 

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