Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <unistd.h>
  4. #include <semaphore.h>
  5. #include <pthread.h>
  6.  
  7. const int BUFFER_SIZE = 10;
  8. bool running = true;
  9. int buffer[BUFFER_SIZE];
  10. int product = 0;
  11. int next_prod = 0, next_consume = 0;
  12. sem_t empty, full;
  13. pthread_mutex_t mutex;
  14.  
  15. void insert_item(int id){
  16.     buffer[next_prod] = product;
  17.     product++;
  18.     printf("Producer %d produced: %d \n", id, buffer[next_prod]);
  19.     next_prod = (next_prod + 1) % BUFFER_SIZE;
  20. }
  21.  
  22. void* producer(void* id){
  23.  
  24.     int producer_id = *((int*)id);
  25.  
  26.     while(running){
  27.  
  28.         sem_wait(&empty);
  29.         pthread_mutex_lock(&mutex, NULL);
  30.  
  31.         insert_item(producer_id);
  32.        
  33.         pthread_mutex_unlock(&mutex, NULL);
  34.         sem_post(&full);
  35.     }
  36. }
  37.  
  38.  
  39.  
  40. int main(int argc, char *argv[]){
  41.  
  42.     if(argc != 4){
  43.         fprintf(stderr, "usage: %s how_long_to_sleep producer_threads consumer_threads\n", argv[0]);
  44.         exit(-1);
  45.     }
  46.  
  47.     int sleep_time = atoi(argv[1]);
  48.     int num_producers = atoi(argv[2]);
  49.     int num_consumers = atoi(argv[3]);
  50.     pthread_t producers[num_producers];
  51.     pthread_t consumers[num_consumers];
  52.  
  53.     pthread_mutex_init(&mutex, NULL);
  54.     sem_init(&empty, 0, BUFFER_SIZE);
  55.     sem_init(&full, 0, 0);
  56.  
  57.     // create producers
  58.     for(int i = 0; i < num_producers; i++){
  59.         pthread_create(&producers[i], NULL, producer, (void*) &i);
  60.     };
  61.  
  62.     // create consumers
  63.     // or(int i = 0; i < num_consumers; i++){
  64.     //  pthread_create(&consumers[i], NULL, consumer, (void*) &i);
  65.     // };
  66.  
  67.  
  68.  
  69.     printf("going to sleep for %i seconds\n", sleep_time);
  70.     sleep(sleep_time);
  71.     running = false;
  72.  
  73.     sem_destroy(&full);
  74.     sem_destroy(&empty);
  75.     pthread_mutex_destroy(&mutex);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement