使用互斥和条件的pthread调度



有人能解释为什么在主线程发出条件信号后可以锁定互斥对象吗?

pthread_t t, v;
pthread_mutex_t m;
pthread_cond_t c;
int res=0;
void* f(void*)
{
    pthread_mutex_lock(&m);
    printf("f-lockedn");
    pthread_cond_wait(&c,&m);
    res=1;
    printf("action!n");
    pthread_mutex_unlock(&m);
    pthread_exit(NULL);
}
void* mainthread(void*)
{
    setbuf(stdout,NULL);
    struct sched_param sp1;
    sp1.sched_priority=0;
    pthread_mutex_init(&m,NULL);
    pthread_cond_init(&c,NULL);
    pthread_setschedparam(t,SCHED_MIN,&sp1);
    pthread_create(&t,NULL,f,NULL);
    for(int i=0;i<10000000;++i);
    pthread_mutex_lock(&m);
    pthread_cond_signal(&c);
    pthread_mutex_unlock(&m);
    //Why can I lock the mutex again immediately???
    pthread_mutex_lock(&m);
    printf("wtf?n");
    res=2;
    pthread_mutex_unlock(&m);
    pthread_join(t,NULL);
    printf("nnres: %dn",res);
    pthread_exit(NULL);
}
int main(int argc, char** argv)
{
    struct sched_param sp0;
    sp0.sched_priority=1;
    pthread_setschedparam(v,SCHED_MIN,&sp0);
    pthread_create(&v,NULL,mainthread,NULL);
    pthread_join(v,NULL);
    return 0;
}

结果将是

f-locked
wtf?
action!
res: 1

我相信,在主线程发出条件信号并释放互斥对象后,互斥对象会立即被f函数锁定,但它的行为不同。

提前感谢!

对不起,我第一次没有正确阅读。你所拥有的是一种种族状况。pthread_cond_wait释放互斥锁,并在发出信号时再次锁定互斥锁。我认为这个答案很好地解释了这一点。

无法保证第三个线程将看到来自二者都pthread_cond_signal将唤醒第三个线程,,但可能不会立即获取互斥

不能保证f会在主线程之前获得锁。

我认为这是因为您没有正确使用pthread_mutex_unlock()。您可以看到

printf("action!n");
pthread_mutex_unlock(&m);
pthread_exit(NULL);

退出此子线程之前,请先解锁互斥对象。当程序执行pthread_mutec_unlock()时,它将首先查找是否有线程被锁定。

因此,如果你这样写,在执行完这条指令后,程序的控制将立即返回到阻塞的主线程。

最新更新