Advertisement
Sri27119

reader

Nov 25th, 2024
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5.  
  6. pthread_mutex_t x = PTHREAD_MUTEX_INITIALIZER;
  7. pthread_mutex_t y = PTHREAD_MUTEX_INITIALIZER;
  8. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  9.  
  10. int readercount = 0;
  11. int writercount = 0;
  12.  
  13. void *reader(void *param) {
  14. int reader_id = *((int *)param);
  15.  
  16. pthread_mutex_lock(&x);
  17. readercount++;
  18. if (readercount == 1) {
  19. pthread_mutex_lock(&y);
  20. }
  21. pthread_mutex_unlock(&x);
  22.  
  23. printf("Reader %d is reading data\n", reader_id);
  24. usleep(100000);
  25. printf("Reader %d is done reading\n", reader_id);
  26.  
  27. pthread_mutex_lock(&x);
  28. readercount--;
  29. printf("Reader %d is leaving. Remaining readers: %d\n", reader_id, readercount);
  30. if (readercount == 0) {
  31. pthread_mutex_unlock(&y);
  32. }
  33. pthread_mutex_unlock(&x);
  34.  
  35. return NULL;
  36. }
  37.  
  38. void *writer(void *param) {
  39. int writer_id = *((int *)param);
  40.  
  41. printf("Writer %d is trying to enter\n", writer_id);
  42. pthread_mutex_lock(&y);
  43. printf("Writer %d is writing data\n", writer_id);
  44. usleep(200000);
  45. printf("Writer %d is done writing\n", writer_id);
  46. pthread_mutex_unlock(&y);
  47.  
  48. return NULL;
  49. }
  50.  
  51. int main() {
  52. int n2, i;
  53. printf("Enter the number of readers and writers: ");
  54. scanf("%d", &n2);
  55. printf("\n");
  56.  
  57. pthread_t readerthreads[n2], writerthreads[n2];
  58. int reader_ids[n2], writer_ids[n2];
  59.  
  60. for (i = 0; i < n2; i++) {
  61. reader_ids[i] = i + 1;
  62. writer_ids[i] = i + 1;
  63. pthread_create(&readerthreads[i], NULL, reader, &reader_ids[i]);
  64. pthread_create(&writerthreads[i], NULL, writer, &writer_ids[i]);
  65. }
  66.  
  67. for (i = 0; i < n2; i++) {
  68. pthread_join(readerthreads[i], NULL);
  69. pthread_join(writerthreads[i], NULL);
  70. }
  71.  
  72. pthread_mutex_destroy(&x);
  73. pthread_mutex_destroy(&y);
  74.  
  75. return 0;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement