2021-04-13

#include <stdio.h>
#include <pthread.h>
 
#define LOOP_COUNT 5			//生产者和消费者各自循环次数
pthread_mutex_t mutex;			//定义一个全局互斥量,在不同函数中
								//初始化和使用
 
void *producer( void *arg );	//生产者线程
void *consumer( void *arg );	//消费者线程
 
int main(int argc , char *argv[]){
	pthread_t thrd_prod , thrd_cons;
 
	pthread_mutex_init( &mutex , NULL );	//初始化互斥量
 
	//创建生产者和消费者线程
	if( pthread_create( &thrd_prod , NULL, producer ,
				NULL ) != 0 )
		oops( "thread create failed." );
	sleep(1);								//保证生产者线程先运行
 
	if( pthread_create( &thrd_cons , NULL, consumer ,
				NULL ) != 0 )
		oops( "thread create failed." );
 
	//等待线程结束
	if( pthread_join( thrd_prod , NULL ) != 0 )
		oops( " wait thread failed.");
	if( pthread_join( thrd_cons , NULL ) != 0 )
		oops( " wait thread failed.");
 
	pthread_mutex_destroy( &mutex );		//关闭互斥量
	return 0;
}
 
void *producer( void *arg){
	int count = 0 ;				//循环计数
 
	while( count++ < LOOP_COUNT ){
		pthread_mutex_lock( &mutex );	//加锁
 
		//成功占有互斥量,接下来可以对缓冲区(仓库)进行生产
		//操作
		printf( " producer put a product to buffer.\n");
		sleep(3);				//休眠3秒, 便于程序观察
 
		pthread_mutex_unlock( &mutex ); //解锁
		sleep(1);				//休眠一秒,防止它又马上占据锁
	}
}
void *consumer( void *arg ){
	int count = 0 ;				//循环计数
 
	while( count++ < LOOP_COUNT ){
//		sleep(2);				//休眠一秒, 便于程序观察
		pthread_mutex_lock( &mutex );	//加锁
 
		//成功占有互斥量,接下来可以对缓冲区(仓库)进行取出
		//操作
		printf( " consumer get a product from buffer.\n");
 
		pthread_mutex_unlock( &mutex ); //解锁
		sleep(1);				//休眠一秒,防止它又马上占据锁
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值