Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4. #include <pthread.h>
  5.  
  6. void* clientThread (void* arg);
  7.  
  8. int freeMugs = 0;
  9. int beersDrank = 0;
  10.  
  11. int freeTaps = 0;
  12. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  13.  
  14. void* clientThread(void* arg) {
  15. int id = *((int*) arg);
  16.  
  17. int i, tap, mug;
  18. int beers = 5;
  19.  
  20. printf("[Klient %d]: Wejscie do pubu!\n", id);
  21.  
  22. for (i = 0; i < beers; i++) {
  23. printf("FREE MUGS: %d \n", freeMugs);
  24. // SEKCJA KRYTYCZNA
  25.  
  26. while(1) {
  27. pthread_mutex_lock(&mutex);
  28. if (freeMugs > 0) {
  29. freeMugs--; // ZAJECIE KUFLA
  30. // OPUSZCZENIE SEKCJI KRYTYCZNEJ
  31. pthread_mutex_unlock(&mutex);
  32.  
  33.  
  34. break;
  35. } else {
  36. pthread_mutex_unlock(&mutex);
  37. }
  38. }
  39.  
  40. tap = 0;
  41. printf("[Klient %d]: Nalanie piwa z kranu %d!\n", id, tap);
  42. usleep(300);
  43. beersDrank++;
  44. printf("[Klient %d]: WYPICIE PIWA!\n", id);
  45. nanosleep((struct timespec[]){{0, 500000000L}}, NULL);
  46. printf("[Klient %d]: Zwrot kufla!\n", id);
  47.  
  48. pthread_mutex_lock(&mutex);
  49. freeMugs++; // ZWROT KUFLA DO PULI
  50. pthread_mutex_unlock(&mutex);
  51. }
  52.  
  53. printf("[Klient %d]: Wyjscie z pubu!\n", id);
  54. return(NULL);
  55. }
  56.  
  57. main () {
  58. pthread_t* client;
  59. int* clientId;
  60.  
  61. int clientsCount, mugsCount, tapsCount, i;
  62.  
  63. // Initial data
  64. printf("\nLiczba klientow: "); scanf("%d", &clientsCount);
  65. printf("\nLiczba kufli: "); scanf("%d", &mugsCount);
  66. tapsCount = 3;
  67.  
  68. // Spawn clients
  69. client = (pthread_t*) malloc(clientsCount * sizeof(pthread_t));
  70. clientId = (int*) malloc(clientsCount * sizeof(int));
  71.  
  72. for (i = 0; i < clientsCount; i++) clientId[i] = i;
  73.  
  74. // Start
  75. printf("Pub zostal otwarty!\n");
  76. freeMugs = mugsCount;
  77. freeTaps = tapsCount;
  78. printf("W pubie zostalo %d wolnych kufli!\n", freeMugs);
  79.  
  80. for (i = 0; i < clientsCount; i++) {
  81. pthread_create(&client[i], NULL, clientThread, &clientId[i]);
  82. }
  83.  
  84. for(i = 0; i < clientsCount; i++){
  85. pthread_join(client[i], NULL);
  86. }
  87.  
  88. printf("DZISIAJ WYPITO %d KUFLI!\n", beersDrank);
  89. printf("Pub zostal zamkniety!\n");
  90.  
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement