#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//静态条件变量
pthread_cond_t cond;//动态条件变量
typedef struct node//链表结构体创建
{
struct node *new;
int data;
}listnode, *linklist;
linklist H=NULL;
linklist p=NULL;
void *test1(void * arg)
{
printf("test1");
pthread_detach(pthread_self());//分离线程
int i=0;
linklist q;
q=H;
while(1)
{
pthread_mutex_lock(&mutex);//上锁
if((p=(linklist)malloc(sizeof(listnode)))==NULL)//链表申请堆区
{
perror("p");
pthread_exit(NULL);
}
p->data=i++;
p->new=NULL;
while(q->new)
{
q=q->new;
}
q->new=p;
printf("%d go\n",p->data);
pthread_cond_signal(&cond);//对正在等待的线程进行唤醒
pthread_mutex_unlock(&mutex);//解锁
sleep(1);
}
pthread_exit(NULL);
}
void * test2(void *arg)
{
printf("test2");
pthread_detach(pthread_self());
linklist q;
q=H;
while(1)
{
pthread_mutex_lock(&mutex);//上锁
while(H->new==NULL)
{
pthread_cond_wait(&cond,&mutex);//最好搭配while使用,等待条件成立,否则休眠
}
q=H->new;
printf("%d lown\n",q->data);
H->new=q->new;
free(q);//!!注意要进行释放。否则会造成内存泄漏
pthread_mutex_unlock(&mutex);//解锁;无必要释放锁
}
pthread_exit(NULL);//终止线程
}
int main()
{
pthread_t pid;
int i=0;
pthread_cond_init(&cond,NULL);//动态条件变量的创建
if((H=(linklist)malloc(sizeof(listnode)))==NULL)//最好有表头
{
perror("H");
}
H->new=NULL;
H->data=0;
pthread_create(&pid,NULL,test1,NULL);
pthread_create(&pid,NULL,test2,NULL);
while(i<20)
{
sleep(1);
i++;
}
free(H);//记得释放
return 0;
}
此份代码可使我在学习的途中所写的,用一个单链表来验证条件变量。完成了生产者和消费者的问题。值得注意的是当多个线程进行抢广播时,要注意卡死现象。
实验现象如下图: