简体   繁体   English

当多个pthread争夺互斥锁时,为什么PTHREAD_MUTEX_ADAPTIVE_NP的行为类似于PTHREAD_MUTEX_TIMED_NP

[英]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. 程序创建一个PTHREAD_MUTEX_ADAPTIVE_NP互斥锁,现在线程A获得了锁。 Three threads(B, C, D) compete for this lock when thread A give it. 当线程A给出锁时,三个线程(B,C,D)争夺该锁。 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. 我认为PTHREAD_MUTEX_ADAPTIVE_NP就像pthread_spinlock一样,就像Kaz Sir在“ 什么是PTHREAD_MUTEX_ADAPTIVE_NP”中的回答:在公平很重要的情况下该方法也不适用:这是一种机会锁定。

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" 跟踪始终是第一个“线程D”->第二个“线程C”->最后一个“线程B”

Sleep cause ADAPTIVE mutex to TIMED mutex? 睡眠会导致ADAPTIVE互斥体变为TIMED互斥体?

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). 但是,自适应互斥锁仅在很短的时间内忙碌旋转(最多有100个PAUSE指令调用的循环)。 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. 这是因为自适应互斥锁适用于非常短,竞争激烈的锁定部分,因此100圈旋转很有可能导致锁定可用。

So given your second-long sleep calls, all your locks are sleeping in the kernel and the busyspin logic is irrelevant. 因此,考虑到您的第二次长时间睡眠调用,您所有的锁都在内核中睡眠,而busyspin逻辑无关紧要。

You can look up the implementation of adaptive mutexes here for pthread_mutex_lock.c . 您可以在此处为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. 万一忙碌的纺纱无法获得锁,nptl会退回到futex锁,我认为这至少是确定性的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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