Mutex, Spinlocks and Cache
Posted: Mon Sep 26, 2011 3:11 pm
Given the following code / scenario. Is it possible that the one CPU that gets the mutex always keeps it due to that the other competing (spinning) cores will have a copy of the value in its cache and therefore when the owner releases the mutex it will never get noticed by the spinning cores?
I have been thinking about introducing a cache invalidate for the mutex, but im not sure if its needed..
Lets say i have 8 cores trying to execute on the same very tight loop;
The reason im asking is that i get very strange results on Virtualbox and it looks like these mutexes are never released and some/all of the other cores just spins forever in mutexSpinLock().
On bochs and on real hardware i have not seen the issue..
regards
Thomas
I have been thinking about introducing a cache invalidate for the mutex, but im not sure if its needed..
Code: Select all
typedef struct mutex
{
int lock;
} mutex;
int test_and_set(int *pointer, int value)
{
#ifdef __GNUC__
__asm__ __volatile__("xchgl %%eax,(%%edx) ": "=a"(value) : "a"(value), "d"(pointer));
return value;
#endif
#ifdef _MSC_VER
__asm
{
mov edx, dword ptr [pointer]
mov eax, value
lock xchg eax, dword ptr [edx]
}
// returning EAX or VALUE
#endif
}
void mutexSpinLock(mutex *p)
{
while(test_and_set(&(p->lock), 1))
{
__asm { rep nop } // No pause? rep nop
}
}
void mutexUnlock(mutex *p)
{
p->lock = 0; // Unlocks the mutex
}
Code: Select all
mutex testMutex;
void test()
{
while(1)
{
mutexSpinLock(&textMutex);
for(int i=0; i < rand(256); i++)
{
}
mutexUnlock(&testMutex);
}
}
On bochs and on real hardware i have not seen the issue..
regards
Thomas