C 12
Question 3 part 3 Guest on 6th May 2022 08:34:59 PM
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <semaphore.h>
  5. #include <fcntl.h>
  6. #include <sys/shm.h>
  7.  
  8. #define BUFF_SIZE 20
  9.  
  10. char buffer[BUFF_SIZE];
  11. int nextIn = 0;
  12. int nextOut = 0;
  13.  
  14. char sem_name1[] = "mutex";
  15. char sem_name2[] = "empty_slots";
  16. char sem_name3[] = "full_slots";
  17. sem_t *empty_slots;
  18. sem_t *full_slots;
  19. sem_t *mutex;
  20.  
  21. typedef struct {
  22. char buffer[BUFF_SIZE];
  23. int nextIn;
  24. int nextOut;
  25. } shared_data;
  26.  
  27. shared_data *shm, *s;
  28.  
  29. void Get(char item)
  30. {
  31.   sem_wait(full_slots);
  32.   sem_wait(mutex);
  33.   item = s->buffer[s->nextOut];
  34.   s->nextOut = (s->nextOut + 1) % BUFF_SIZE;
  35.   sem_post(mutex);
  36.   printf("%u is Consuming %c ...\n", pthread_self(), item);
  37.   sem_post(empty_slots);
  38. }
  39.  
  40. void * Consumer()
  41. {
  42.     int i;
  43.     char  item;
  44.     for(i = 0; i < 10; i++)
  45.     {
  46.       sleep(rand()%9);
  47.       Get(item);
  48.     }
  49. }
  50.  
  51. void main()
  52. {
  53.         mutex=sem_open(sem_name1, O_CREAT,0644, 1);
  54.         full_slots=sem_open(sem_name3, O_CREAT,0644, 0);
  55.         empty_slots=sem_open(sem_name2, O_CREAT,0644, 10);
  56.  
  57.         //allocate the shared memory segment
  58.         key_t key;
  59.         key = 1234;
  60.         //locate the segment
  61.         int shmid;
  62.         if ((shmid = shmget(key, sizeof(shared_data),0666)) <0)
  63.         {
  64.                 perror("Shmget");
  65.                 exit(1);
  66.         }
  67.         //attach to the segment
  68.         if ((shm = (shared_data *) shmat(shmid, NULL, 0))==(shared_data *) -1)
  69.         {
  70.                 perror("Shmat");
  71.                 exit(1);
  72.         }
  73.        
  74.         s=shm;
  75.         s->nextOut = 0;
  76.        
  77.         //Consumer();
  78.  
  79.         pthread_t pid[2];
  80.         pthread_create(&pid[0], NULL, Consumer, NULL);
  81.         pthread_create(&pid[1], NULL, Consumer, NULL);
  82.         pthread_create(&pid[2], NULL, Consumer, NULL);
  83.  
  84.         pthread_join(pid, NULL);
  85.  
  86.         shmdt((void *) shm);
  87.        
  88. }

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.