Hardware Support Locking
Last updated
void mutex_lock (int *mutex)
{
unsigned int v;
/* Bit 31 was clear, we got the mutex. (this is the fastpath). */
if (atomic_bit_test_set (mutex, 31) == 0)
return;
atomic_increment (mutex);
while (1)
{
if (atomic_bit_test_set (mutex, 31) == 0)
{
atomic_decrement (mutex);
return;
}
/* We have to wait now. First make sure the futex value we are monitoring is truly negative (i.e. locked). */
v = *mutex;
if (v >= 0)
continue;
lll_futex_wait (mutex, v);
}
}void mutex_unlock (int *mutex)
{
/* Adding 0x80000000 to the counter results in 0 if and only if there are not other interested threads - we can return (this is the fastpath). */
if (atomic_add_zero (mutex, 0x80000000))
return;
/* There are other threads waiting for this mutex, wake one of them up. */
lll_futex_wake (mutex, 1);
}# define atomic_add_zero(mem, value) \
({ __typeof (value) __atg13_value = (value); \
atomic_exchange_and_add (mem, __atg13_value) == -__atg13_value; })