Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. #include "stdio.h"
  2. #include "unistd.h"
  3. #include "pthread.h"
  4. #include "stdlib.h"
  5. #include "errno.h"
  6. #include "limits.h"
  7. #include "math.h"
  8. #include "semaphore.h"
  9. #include "string.h"
  10.  
  11. #define BUFFER_SIZE 100
  12.  
  13. #define PREFIX "MARCIN"
  14.  
  15. sem_t wr, rd1, rd2, rd3;
  16.  
  17. void emptyBuffer( char* buff);
  18. void *threadCzytelnik(void *arg);
  19.  
  20.  
  21.  
  22.  
  23.  
  24. struct targs{
  25. int numWatku;
  26. };
  27. char common[BUFFER_SIZE];
  28. int koniecPliku = 0;
  29. int main()
  30. {
  31. FILE *fp;
  32.  
  33. emptyBuffer(common);
  34. sem_init(&wr, 0, 1);
  35. sem_init(&rd1, 0, 0);
  36. sem_init(&rd2, 0, 0);
  37. sem_init(&rd3, 0, 0);
  38. pthread_attr_t attrs;
  39. pthread_attr_init(&attrs);
  40. //pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED );
  41.  
  42. pthread_t threadId[3];
  43. fp = fopen("/etc/passwd","r");
  44. struct targs watki[3];
  45. {
  46. int i = 0;
  47. for(;i < 3; i++)
  48. {
  49. watki[i].numWatku = i+1;
  50. pthread_create(&threadId[i], &attrs, threadCzytelnik, &watki[i]);
  51. pthread_detach(threadId[i]);
  52. }
  53. }
  54. char *l;
  55. while( 1 ) {
  56. sem_wait(&wr);
  57. l = fgets(common, BUFFER_SIZE, fp);
  58. if(l==0) break;
  59. sem_post(&rd1);
  60.  
  61. }
  62. fclose(fp);
  63. koniecPliku = 1;
  64. sem_post(&rd1);
  65. }
  66.  
  67. void emptyBuffer( char* buff)
  68. {
  69. {
  70. int i = 0;
  71. for(;i<BUFFER_SIZE;i++)
  72. {
  73. buff[i] = 0;
  74. }
  75. }
  76. }
  77.  
  78.  
  79. void *threadCzytelnik(void *arg)
  80. {
  81.  
  82. struct targs *argptr = (struct targs*) arg;
  83.  
  84. char nazwaPliku[80];
  85. snprintf(nazwaPliku, 80, "./MATEUSZ%d", argptr->numWatku);
  86. FILE *fp = fopen(nazwaPliku, "w");
  87. while(1)
  88. {
  89. if(argptr->numWatku==1) sem_wait(&rd1);
  90. if(argptr->numWatku==2) sem_wait(&rd2);
  91. if(argptr->numWatku==3) sem_wait(&rd3);
  92. if(koniecPliku)
  93. {
  94. fflush(fp);
  95. fclose(fp);
  96. pthread_exit(0);
  97. }
  98. fwrite(common, sizeof(char), strlen(common), fp);
  99. printf("%d-%s\n", argptr->numWatku, common);
  100. fflush(stdout);
  101. if(argptr->numWatku==1) sem_post(&rd2);
  102. if(argptr->numWatku==2) sem_post(&rd3);
  103. if(argptr->numWatku==3) sem_post(&wr);
  104. }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement