生产者消费者问题源代码

  • 格式:txt
  • 大小:3.04 KB
  • 文档页数:2

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

#define NUM_THREADS_P 5
#define NUM_THREADS_C 5
#define MAX_BUFFER 20
#define RUN_TIME 20
int buffer[MAX_BUFFER],number=1;
int produce_pointer=0,consume_pointer=0;
sem_t producer_semaphore,consumer_semaphore,buffer_mutex;
pthread_t threads_p[NUM_THREADS_P]; /*producer*/
pthread_t threads_c[NUM_THREADS_C]; /*consumer*/
void *producer_thread(void *tid);
void *consumer_thread(void *tid);
void showbuf();
void handler(){
int i;
for(i=0;ipthread_cancel(threads_p[i]);
for(i=0;ipthread_cancel(threads_c[i]);
}

int main(){
int i;
signal(SIGALRM,handler);
sem_init(&producer_semaphore,0,MAX_BUFFER);
sem_init(&consumer_semaphore,0,0);
sem_init(&buffer_mutex,0,1);
for(i=0;ibuffer[i]=0;

for(i=0;ipthread_create(&threads_p[i],NULL,(void*)producer_thread,(void*)(i+1));
for(i=0;ipthread_create(&threads_c[i],NULL,(void*)consumer_thread,(void *)(i+1));
alarm(RUN_TIME);

for(i=0;ipthread_join(threads_p[i],NULL);
for(i=0;ipthread_join(threads_c[i],NULL);

sem_destroy(&producer_semaphore);
sem_destroy(&consumer_semaphore);
sem_destroy(&buffer_mutex);
return 0;
}

void *producer_thread(void *tid){
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
while(1){
sem_wait(&producer_semaphore);
srand((int)time(NULL)*(int)tid);
sleep(rand()%2+1);
while((produce_pointer+1)%20==consume_pointer);

sem_wait(&buffer_mutex);
if (number>20) number=1;
buffer[produce_pointer]=number++;
produce_pointer=(produce_pointer+1)%20;

if(produce_pointer==0){
printf("producer:%d pointer_p:%2d produced:%2d\n",(int)tid,19,buffer[19]);
}
else{
printf("producer:%d pointer_p:%2d produced:%2d\n",(int)tid,produce_pointer-1,buffer[produce_pointer-1]);
}
showbuf();
sem_post(&buffer_mutex);

sem_post(&consumer_semaphore);
srand((int)time(NULL)*(int)tid);
sleep(rand()%5+1);
}
return ((void*)0);
}

void *consumer_thread(void *tid){

pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
while(1){
sem_wait(&consumer_semaphore);
srand((int)time(NULL)*(int)tid);
sleep(rand()%2+1);

sem_wait(&buffer_mutex);
printf("consumer:%d pointer_c:%2d consumed:%2d\n",(int)tid,consume_pointer,buffer[consume_pointer]);
buffer[consume_pointer]=0;
consume_pointer=(consume_pointer+1)%20;
showbuf();
sem_post(&buffer_mutex);

sem_post(&producer_semaphore);
srand((int)time(NULL)*(int)tid);
sleep(rand()%5+1);
}
return ((void*)0);
}

void showbuf(){
int

i;
printf("buffer:");
for(i=0;iprintf("%2d ",buffer[i]);
}
printf("\n\n");
}

下载文档原格式

  / 2
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。