#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;i
for(i=0;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;i
for(i=0;i
for(i=0;i
alarm(RUN_TIME);
for(i=0;i
for(i=0;i
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;i
}
printf("\n\n");
}