红联Linux门户
Linux帮助

不明白,球赐教,很迷惑

发布时间:2012-04-18 17:19:52来源:红联作者:wuyuwww
[code]#include
#include
#include
#include

pthread_cond_t taxiCond=PTHREAD_COND_INITIALIZER;

pthread_mutex_t taxiMutex=PTHREAD_MUTEX_INITIALIZER;
void * traveler_arrive(void *name)
{
int ret;
printf("Traveler %s needs a taxi now1\n",name);
ret=pthread_mutex_lock(&taxiMutex);
if (ret==0) printf("cond is locked\n");
pthread_cond_wait(&taxiCond,&taxiMutex);
printf("test\n");
pthread_mutex_unlock(&taxiMutex);
printf("%s got a taxi\n",name);
printf("traver thread sucess and exit\n");
pthread_exit((void *)0);
}

void * taxi_arrive(void * name)
{
int ret;
printf("taxi %s arrive \n",name);

pthread_mutex_unlock(&taxiMutex);
ret=pthread_cond_signal(&taxiCond);
if(ret==0) printf("cond is lived\n");

pthread_mutex_unlock(&taxiMutex);
printf("taxi thread sucess and exit\n");
pthread_exit((void *)0);
}

void main()
{
pthread_t thread;
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);

pthread_create(&thread,&threadAttr,taxi_arrive,(void *)("Jack"));
sleep(10);

pthread_create(&thread,&threadAttr,traveler_arrive,(void *)("Susan"));
sleep(10);

pthread_create(&thread,&threadAttr,taxi_arrive,(void *)("Mike"));
sleep(10);

return ;

}
[/code]输出为:
taxi Jack arrive
cond is lived
taxi thread sucess and exit
Traveler Susan needs a taxi now1
cond is locked
taxi Mike arrive
test
Susan got a taxi
traver thread sucess and exit
cond is lived
taxi thread sucess and exit


感觉输出的结果怎么很奇怪啊:怎么 Susan got a taxi在cond is lived
那不就是信号还没出发 而那边的线程就已经得到信号了啊 这是怎么回事啊 她不是应该在等待条件为真的时候才可以将挂起的线程激活吗 怎么结果是这个样子
文章评论

共有 0 条评论