繁体   English   中英

带互斥和条件的pthread调度

[英]pthread scheduling with mutex and condition

有人可以解释为什么在信号通知条件后可以锁定主线程吗?

pthread_t t, v;
pthread_mutex_t m;
pthread_cond_t c;
int res=0;
void* f(void*)
{
    pthread_mutex_lock(&m);
    printf("f-locked\n");
    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("\n\nres: %d\n",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()时,它将首先查找是否有某个线程被锁定。

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

暂无
暂无

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

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