1. 程式人生 > 其它 >mutex_lock 函式分析

mutex_lock 函式分析

path:kernel/locking/mutex.c

function source code:

void __sched mutex_lock(struct mutex *lock)
{
    might_sleep();

    if (!__mutex_trylock_fast(lock))
        __mutex_lock_slowpath(lock);
}
EXPORT_SYMBOL(mutex_lock);

從上面程式碼可以看出 mutex_lock 函式有兩條路徑,首先嚐試__mutex_trylock_fast(lock) 快速路徑,如果嘗試失敗就進入 __mutex_lock_slowpath(lock)

 慢速路徑

__mutex_trylock_fast(lock)
        atomic_long_try_cmpxchg_acquire(&lock->owner, &zero, curr)  //判斷 curr 的值是否 小於等於 zero
                arch_atomic_long_try_cmpxchg_acquire(v, old, new);
                        arch_atomic_try_cmpxchg_acquire(v, (int *)old, new);
                                arch_atomic_try_cmpxchg_acquire(atomic_t *v, int *old, int new)

判斷curr 的值是否小於等於 0 如果小於等於 0 則進入 __mutex_lock_slowpath(lock) 否則就直接返回

__mutex_lock_slowpath(lock)
        __mutex_lock_common(lock, state, subclass, nest_lock, ip, NULL, false);

__mutex_lock_slowpath(lock) 鎖定互斥鎖 ,可能會中斷