linux下C語言實現生產者消費者問題
阿新 • • 發佈:2019-02-16
問題描述:
緩衝區大小為N,生產者產生物品放到緩衝區,消費者將物品從緩衝區移走
互斥關係:
對緩衝區得訪問需要互斥,包括生產者和生產者之間、消費者和消費者之間、生產者和消費者之間。
同步關係:
當緩衝區滿時生產者程序需要等待,當緩衝區空時消費者程序需要等待。
解題思路:
用訊號量解決生產者消費者問題。
- 互斥:
有節緩衝區是一個臨界資源,對臨界資源得訪問需要設定一個訊號量mutex
- 同步:
設定兩個同步訊號量empty和full,其初值分別為n、0,用於臨界資源得具體數目,同時也可以表示等待條件
具體如下:
程式碼實現:
#include <stdio.h>
#include <pthread.h>
#include<semaphore.h>
sem_t empty,full; //定義全域性同步訊號量empty,full
pthread_mutex_t mutex; //定義一個全域性互斥量,在不同函式中
int buffer_count=0; //定義一個全域性變數,表示管道內得產品數目
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 ); //初始化互斥量
sem_init (&empty, 0, 5); //初始化empty訊號量
sem_init (&full, 0, 0); //初始化full訊號量
//建立生產者和消費者執行緒
if( pthread_create( &thrd_prod , NULL, producer ,
NULL ) != 0 )
printf( "thread create failed." );
if( pthread_create( &thrd_cons , NULL, consumer ,
NULL ) != 0 )
printf( "thread create failed." );
//等待執行緒結束
if( pthread_join( thrd_prod , NULL ) != 0 )
printf( " wait thread failed.");
if( pthread_join( thrd_cons , NULL ) != 0 )
printf( " wait thread failed.");
sem_destroy (&full); //釋放同步量
sem_destroy(&empty); //釋放同步量
pthread_mutex_destroy( &mutex ); //關閉互斥量
return 0;
}
void *producer( void *arg){
while(1){
sem_wait(&empty); //empty-1
pthread_mutex_lock( &mutex ); //加鎖
//成功佔有互斥量,接下來可以對緩衝區(倉庫)進行生產
//操作
printf( " producer put a product to buffer.");
buffer_count++;
printf("the buffer_count is %d\n",buffer_count) ;
pthread_mutex_unlock( &mutex ); //解鎖
sem_post(&full); //full+1
}
}
void *consumer( void *arg ){
while(1)
{
sem_wait(&full); //full-1
pthread_mutex_lock( &mutex ); //加鎖
//成功佔有互斥量,接下來可以對緩衝區(倉庫)進行取出
//操作
printf( " consumer get a product from buffer.");
buffer_count--;
printf("the buffer_count is %d\n",buffer_count) ;
pthread_mutex_unlock( &mutex ); //解鎖
sem_post(&empty); //empty-1
}
}
結果如下: