简体   繁体   中英

why PTHREAD_MUTEX_ADAPTIVE_NP behaves like PTHREAD_MUTEX_TIMED_NP when more than one pthreads compete for the mutex lock

Program creates a PTHREAD_MUTEX_ADAPTIVE_NP mutex, and now thread A gets the lock. Three threads(B, C, D) compete for this lock when thread A give it. What I wonder is, why the thread which have waited for the longest time always first gets this lock and then the second longest time thread...and so on.

I think PTHREAD_MUTEX_ADAPTIVE_NP is like pthread_spinlock just like answer of Kaz Sir in What is PTHREAD_MUTEX_ADAPTIVE_NP : The approach is also not suitable in situations in which fairness is important: it is an opportunistic lock.

Code like this

`Thread A:
    main() {
        mutex_lock;
        pthread_create(B);
        pthread_create(C);
        pthread_create(D);
        sleep(3);
        mutex_unlock;
}`

Thread B() {
    sleep(2);
    mutex_lock;
    printf("Thread B");
    mutex_unlock;
}

Thread C() {
    sleep(1);
    mutex_lock;
    printf("Thread C");
    mutex_unlock;
}

Thread D() {
    mutex_lock;
    printf("Thread D");
    mutex_unlock;
}

The trace is always first "Thread D" -> Second "Thread C" -> last "Thread B"

Sleep cause ADAPTIVE mutex to TIMED mutex?

Your basic idea is correct. However, the adaptive mutex only busy-spins for a very short time (a loop with at most 100 PAUSE instruction calls). As soon as it enters the kernel-sleep phase, it behaves like a regular mutex again.

This is because adaptive mutexes are meant for very short, very aggressively contended locked sections, so that there is a reasonable chance that a 100-loop spin will lead to the lock becoming available.

So given your second-long sleep calls, all your locks are sleeping in the kernel and the busyspin logic is irrelevant.

You can look up the implementation of adaptive mutexes here for pthread_mutex_lock.c . In case the busy-spin fails to acquire the lock, nptl falls back to futex locks, which I believe are at least a deterministic order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM