Untitled

mail@pastecode.io avatarunknown
plain_text
a month ago
1.7 kB
1
Indexable
Never
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define BUFFER_SIZE 20

int producer_idx = 0;
int consumer_idx = 0;
int buffer [BUFFER_SIZE];

pthread_t* producer_threads;
pthread_t* consumer_threads;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void insert(int item){
   pthread_mutex_lock( &mutex );
   buffer[producer_idx] = item;
   producer_idx = (producer_idx + 1) % BUFFER_SIZE;
   pthread_mutex_unlock( &mutex );
   sleep(1); 
}

int remove_item(){
   int item;
   pthread_mutex_lock( &mutex );
   item = buffer[consumer_idx];
   consumer_idx=(consumer_idx+1) % BUFFER_SIZE;
   pthread_mutex_unlock( &mutex );
   sleep(1); 
   return item;
}

void * producer(void * param){
   int item;
   while(1){
      item =  rand() * pthread_self() % BUFFER_SIZE ;
      insert(item);
      printf("Thread: %d inserted: %d\n",pthread_self(), item);
   }
}

void * consumer(void * param){
   int item;
   while(1){
   	item = remove_item();
   	printf("Thread: %d removed: %d\n",pthread_self(), item);
   }
}

int main(int argc, char * argv[])
{
    int producers = atoi(argv[1]);
    int consumers = atoi(argv[2]);
    int i;
    producer_threads = (pthread_t*) malloc(sizeof(pthread_t) * producers);
    consumer_threads = (pthread_t*) malloc(sizeof(pthread_t) * consumers);

    for (i = 0; i < producers; i++)
       pthread_create(&producer_threads[i], NULL, producer,NULL);
    for (i = 0; i < consumers; i++)
       pthread_create(&consumer_threads[i], NULL, consumer, NULL); 

    for (i = 0; i < producers; i++)
       pthread_join(producer_threads[i], NULL);

    for (i = 0; i < consumers; i++)
       pthread_join(consumer_threads[i], NULL);
}