Advertisement
Guest User

Untitled

a guest
Apr 1st, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. #include <sys/types.h>
  7.  
  8. #define CANS 2
  9. #define CLIENTS 6
  10.  
  11. void * func (void * arg_wsk);
  12. struct pub {int cansTab[CANS]; pthread_mutex_t* mutex; pthread_mutex_t* mutex2;};
  13. static int threadNumber= 0;
  14.  
  15. int main(){
  16. pthread_mutex_t mutex, mutex2;
  17.  
  18. struct pub pub1;
  19. pub1.mutex = &mutex;
  20. pub1.mutex2 = &mutex2;
  21. int i;
  22. for(i=0; i<CANS; i++)
  23. pub1.cansTab[i] = 1;
  24.  
  25. pthread_t tid[CLIENTS];
  26.  
  27. for(i=0; i < CLIENTS; i++)
  28. {
  29. pthread_create(&tid[i], NULL, func, &pub1);
  30. }
  31.  
  32. for(i=0; i < CLIENTS; i++)
  33. {
  34. pthread_join(tid[i],NULL);
  35.  
  36. }
  37. }
  38.  
  39. void * func (void * arg_wsk){
  40. struct pub *pub_wsk = arg_wsk;
  41.  
  42. int thread_nr = threadNumber++;
  43.  
  44. int i, canNr, useCanNr;
  45. for(i=0;i<2;i++)
  46. {
  47. printf("Klient %d: chcialby wypic %d piwo \n", thread_nr, 1+i);
  48.  
  49. while(1)
  50. {
  51. {
  52. if(pthread_mutex_trylock(&pub_wsk->mutex[canNr%CANS])==0)
  53. {
  54. useCanNr = canNr%CANS;
  55. break;
  56. }
  57. else { canNr++; }
  58. }
  59. pthread_mutex_lock(pub_wsk->mutex2);
  60. usleep(500);
  61. pthread_mutex_unlock(pub_wsk->mutex2);
  62. printf("Klient %d: ma kufel. Pije %d piwo z %d kufla \n", thread_nr, i+1, useCanNr+1);
  63. usleep(2500);
  64. printf("Klient %d: wypił %d piwo. Odklada %d kufel \n", thread_nr, i+1, useCanNr+1);
  65. pthread_mutex_unlock (&pub_wsk->mutex[useCanNr]);
  66. }
  67. return(NULL);
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement