#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); //休眠一秒,防止它又马上占据锁
}
}
04-21
808
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-05
714
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-26
2万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)