2024年6月9日发(作者:)

//获取锁

LLL_MUTEX_LOCK (mutex);

assert (mutex->__data.__owner == 0);

mutex->__data.__count = 1;

}

//适应锁 等待解锁后重新竞争

else if (__builtin_expect (PTHREAD_MUTEX_TYPE (mutex)

== PTHREAD_MUTEX_ADAPTIVE_NP, 1))

{

if (! __is_smp)

goto simple;

if (LLL_MUTEX_TRYLOCK (mutex) != 0)

{

int cnt = 0;

int max_cnt = MIN (MAX_ADAPTIVE_COUNT,

mutex->__data.__spins * 2 + 10);

//循环等待获得锁

do

{

if (cnt++ >= max_cnt)

{

LLL_MUTEX_LOCK (mutex);

break;

}

atomic_spin_nop ();

}

while (LLL_MUTEX_TRYLOCK (mutex) != 0);

mutex->__data.__spins += (cnt - mutex->__data.__spins) / 8;

}

assert (mutex->__data.__owner == 0);

}

//检错锁

else

{

pid_t id = THREAD_GETMEM (THREAD_SELF, tid);

assert (PTHREAD_MUTEX_TYPE (mutex) == PTHREAD_MUTEX_ERRORCHECK_NP);

//线程持有锁返回EDEADLK

if (__glibc_unlikely (mutex->__data.__owner == id))

return EDEADLK;

//跳转到普通锁加锁

goto simple;

}

pid_t id = THREAD_GETMEM (THREAD_SELF, tid);

//记录线程id

mutex->__data.__owner = id;

#ifndef NO_INCR

++mutex->__data.__nusers;

#endif

LIBC_PROBE (mutex_acquired, 1, mutex);

return 0;

}