- 论坛徽章:
- 2
|
#include"all.h"
typedef struct link
{
int data;
struct link *next;
}Node;
Node *head=NULL;
pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cnd=PTHREAD_COND_INITIALIZER;
void writequeue(void *arg)
{
Node *p=NULL;
p=(Node *)malloc(sizeof(struct link));
if(p==NULL)
{
printf("Allocate space failed!\n");
exit(-1);
}
p->data=(int)arg;
p->next=NULL;
pthread_mutex_lock(&mut);
if(head==NULL)
head=p;
else
{
p->next=head;
head=p;
}
//pthread_cond_signal(&cnd);
pthread_mutex_unlock(&mut);
pthread_cond_signal(&cnd);
pthread_exit(NULL);
}
void readqueue(void *arg)
{
Node *p=NULL;
pthread_mutex_lock(&mut);
while(head==NULL)
pthread_cond_wait(&cnd,&mut);
printf("Read the headueue from head: \n");
for(p=head;p!=NULL;p=p->next)
{
printf("%d \n",p->data);
}
printf("\n");
pthread_mutex_unlock(&mut);
pthread_exit(NULL);
}
int main(void)
{
pthread_t tid[5];
pthread_t tidrd;
int i=5;
int err;
Node *p;
for(i=0;i<5;i++)
{
err=pthread_create(&tid,NULL,(void *)writequeue,(void *)(i+1));
if(err!=0)
{
printf("Create pthread failed!\n");
exit(-1);
}
}
sleep(1);
for(p=head;p;p=p->next)
printf("%d \n",p->data);
err=pthread_create(&tidrd,NULL,(void *)readqueue,NULL);
if(err!=0)
{
printf("Create pthread failed!\n");
exit(-1);
}
for(i=0;i<5;i++)
pthread_join(tid,NULL);
pthread_join(tidrd,NULL);
pthread_mutex_destroy(&mut);
pthread_cond_destroy(&cnd);
exit(0);
}
期望结果是5 4 3 2 1,但是结果是相反的,若去掉sleep(1),结果却是5,在gdb下结果是正确的。不知错哪里了,望各位大神不吝赐教! |
|