在linux下条件变量的证明

#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;
}

此份代码可使我在学习的途中所写的,用一个单链表来验证条件变量。完成了生产者和消费者的问题。值得注意的是当多个线程进行抢广播时,要注意卡死现象。

实验现象如下图:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值