gpt4 book ai didi

c - pthread_cond_broadcast 不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 07:38:02 25 4
gpt4 key购买 nike

我写了这个程序:

pthread_cond_t placeFootCondition;

pthread_mutex_t rf,lf;

void* rss(void* in){
while(1){
pthread_mutex_lock(&rf);
printf ( "rss: waiting for condition\n" );
pthread_cond_wait(&placeFootCondition,&rf);
printf ( " Right Single Support \n" );
sleep(1);
pthread_mutex_unlock(&rf);

}
}

void* lss(void* in){
while(1){
pthread_mutex_lock(&lf);
printf ( "lss: waiting for condition\n" );
pthread_cond_wait(&placeFootCondition,&lf);
printf ( "Left Single Support \n" );
sleep(1);
pthread_mutex_unlock(&lf);

}
}


int main(){
int rc;
pthread_mutex_init(&rf,NULL);
pthread_mutex_init(&lf,NULL);
pthread_cond_init(&placeFootCondition,NULL);
pthread_create(&t1,NULL,rss,NULL);
pthread_create(&t2,NULL,lss,NULL);
sleep(1);
rc=pthread_cond_broadcast(&placeFootCondition);
if(rc!=0) printf ( "rc=%i\n",rc );
sleep(5);
}

但是程序的输出是

rss: waiting for condition
lss: waiting for condition
Right Single Support
rss: waiting for condition

pthread_cond_broadcast(&placeFootCondition) 不应该唤醒所有线程???

最佳答案

这是你正在做的:

pthread_cond_wait(&placeFootCondition,&rf); /* First thread uses rf mutex. */

pthread_cond_wait(&placeFootCondition,&lf); /* Second thread uses lf mutex. */

这是the standard说到使用不同的互斥量:

When a thread waits on a condition variable, having specified a particular mutex to either the pthread_cond_timedwait() or the pthread_cond_wait() operation, a dynamic binding is formed between that mutex and condition variable that remains in effect as long as at least one thread is blocked on the condition variable. During this time, the effect of an attempt by any thread to wait on that condition variable using a different mutex is undefined.


最重要的是,在等待条件变量时,您应该在每个线程中使用相同的互斥体。

关于c - pthread_cond_broadcast 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7281801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com