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

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.