Guest User

Untitled

a guest
May 26th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include "sem.h"
  6.  
  7. Semafor *sx = new Semafor(3);
  8.  
  9. pthread_mutex_t most;
  10. int *sam;
  11. int n;
  12.  
  13. int miastoA() {
  14. int x=0;
  15. for (int i=0;i<n;i++)
  16. if (sam[i]==0) x++;
  17. return x;
  18. }
  19.  
  20. int miastoB() {
  21. int x=0;
  22. for (int i=0;i<n;i++)
  23. if (sam[i]==1) x++;
  24. return x;
  25. }
  26.  
  27. int kolejkaA() {
  28. int x=0;
  29. for (int i=0;i<n;i++)
  30. if (sam[i]==2) x++;
  31. return x;
  32. }
  33.  
  34. int kolejkaB() {
  35. int x=0;
  36. for (int i=0;i<n;i++)
  37. if (sam[i]==3) x++;
  38. return x;
  39. }
  40.  
  41. int imost() {
  42. for (int i=0;i<n;i++) {
  43. if ((sam[i]==4) || (sam[i]==5)) return i;
  44. }
  45. return 0;
  46. }
  47.  
  48. void msg() {
  49. printf("A-%d %d>>> [",miastoA(),kolejkaA());
  50. int i=imost();
  51. if (sam[i]==4) printf(">> %d >>",i+1);
  52. else printf("<< %d <<",i+1);
  53. printf("] <<<%d %d-B\n",kolejkaB(),miastoB());
  54. }
  55.  
  56. void czekaj() {
  57. srand(time(NULL));
  58. sleep(rand()%15+3);
  59. }
  60.  
  61. void *pmost(void * arg) {
  62. int s;
  63. s=(int)arg;
  64. while(1) {
  65.  
  66. if ((sam[s]==0) || (sam[s]==1)) {
  67. czekaj();
  68. if (sam[s]==0) sam[s]=2;
  69. else sam[s]=3;
  70. }
  71.  
  72. if ((sam[s]==2) || (sam[s]==3)) {
  73. sx->P();
  74. pthread_mutex_lock(&most);
  75. if (sam[s]==2) sam[s]=4;
  76. else sam[s]=5;
  77. //printf("Samochod nr %d przejezdza przez most.\n",s+1);
  78. msg();
  79. sleep(2);
  80.  
  81.  
  82. pthread_mutex_unlock(&most);
  83. if (sam[s]==4) sam[s]=0;
  84. else sam[s]=1;
  85. //printf("Samochod nr %d przejechal przez most.\n",s+1);
  86. //msg();
  87. sx->V();
  88. }
  89. }
  90. }
  91.  
  92. int main(int argc, char * argv[]) {
  93.  
  94. if (argc<2) {
  95. printf("Nie podales ilosci samochodow!\n");
  96. return -1;
  97. }
  98. n=atoi(argv[1]);
  99.  
  100. int i;
  101. pthread_t thread[n];
  102.  
  103.  
  104.  
  105. sam = new int [n];
  106.  
  107. srand(time(NULL));
  108. for (i=0;i<n;i++)
  109. sam[i]=rand()%4;
  110.  
  111. pthread_mutex_init(&most,NULL);
  112.  
  113. for(i=0;i<n;i++)
  114. pthread_create(&thread[i],NULL,pmost,(void *)i);
  115.  
  116. for(i=0;i<n;i++)
  117. pthread_join(thread[i],NULL);
  118.  
  119. pthread_mutex_destroy(&most);
  120. delete sam;
  121.  
  122. return 0;
  123. }
Add Comment
Please, Sign In to add comment