2.6作业

本文详细介绍了如何使用C语言中的pthread库,通过条件变量和互斥锁实现生产者和消费者线程之间的同步,确保资源安全并发访问。
摘要由CSDN通过智能技术生成

两个线程实现同步代码示例

#include <myhead.h>

//1、定义条件变量
pthread_cond_t cond;

//11、定义互斥锁
pthread_mutex_t mutex; 

//定义生产者线程
void *task1(void *arg)
{
	sleep(1);
	printf("%#lx:生产了两辆汽车\n", pthread_self());

	//3、唤醒等待队列中的所有线程
	pthread_cond_broadcast(&cond);

	//退出线程
	pthread_exit(NULL);
}

//定义消费者线程
void *task2(void *arg)
{

	//33、获取锁资源
	pthread_mutex_lock(&mutex);

	//4、等待生产者线程的资源    
	pthread_cond_wait(&cond, &mutex);


	printf("%#lx:购买了一辆汽车\n", pthread_self());

	//44、释放锁资源
	pthread_mutex_unlock(&mutex);

	//退出线程
	pthread_exit(NULL);
}


int main(int argc, const char *argv[])
{
	//定义两个线程号
	pthread_t tid1, tid2, tid3, tid4, tid5;


	//2、初始化条件变量
	pthread_cond_init(&cond, NULL);
	//22、初始化互斥锁
	pthread_mutex_init(&mutex, NULL);

	//创建生产者线程
	if(pthread_create(&tid1, NULL, task1, NULL) != 0)
	{
		printf("tid1 create error\n");
		return -1;
	}

	//创建消费者线程
	if(pthread_create(&tid2, NULL, task2, NULL) != 0)
	{
		printf("tid2 create error\n");
		return -1;
	}
	if(pthread_create(&tid3, NULL, task2, NULL) != 0)
	{
		printf("tid3 create error\n");
		return -1;
	}


	printf("tid1 = %#lx, tid2 = %#lx, tid3 = %#lx\n",tid1, tid2, tid3);

	//回收线程资源
	pthread_join(tid1 , NULL);
	pthread_join(tid2 , NULL);
	pthread_join(tid3, NULL);

	//5、销毁条件变量
	pthread_cond_destroy(&cond);

	//55、销毁互斥锁
	pthread_mutex_destroy(&mutex);

	return 0;
}

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值