Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "domaci1.h"
  4. #define UNLOCKED 0
  5. #define WAITING 1
  6. #define TIMED_OUT 2
  7.  
  8. typedef struct
  9. {
  10. int flag;
  11. struct node* next;
  12. int id;
  13. }node;
  14.  
  15. node* tail;
  16. double minDelta = 1;
  17.  
  18. int lock_n_threads_with_timeout(int id, int* local, int timeout)
  19. {
  20. double start = get_time();
  21. double dTimeout = (double)timeout/1000;
  22. int startInt = (int) start;
  23. node* novi = malloc(sizeof(node));
  24. novi->id=id;
  25. novi->flag=WAITING;
  26. novi->next=NULL;
  27. node* stari=(node*) get_and_set(&tail,novi);
  28. local[0]=novi;
  29. if(stari!=NULL)
  30. {
  31. stari->next=novi;
  32. while(1)
  33. {
  34. sleep(2);
  35. double end = get_time();
  36. int endInt = (int) end;
  37. double threadTime = end-start;
  38. if(threadTime<minDelta)
  39. {
  40. minDelta=threadTime;
  41. }
  42. if(threadTime>dTimeout)
  43. {
  44. if(novi->next==NULL)
  45. {
  46. if(!compare_and_set(&tail,novi,stari))
  47. {
  48. while(novi->next==NULL)
  49. {
  50. sleep(0);
  51. }
  52. compare_and_set(&novi->flag,WAITING,TIMED_OUT);
  53. }
  54. }
  55. else
  56. {
  57. while(1)
  58. {
  59. if(!compare_and_set(&novi->flag,WAITING,UNLOCKED))
  60. {
  61. node* temp=novi;
  62. novi=novi->next;
  63. free(temp);
  64. }
  65. else
  66. {
  67. break;
  68. }
  69. }
  70.  
  71. }
  72. return 0;
  73. }
  74.  
  75. if(novi->flag==0)
  76. {
  77. break;
  78. }
  79. }
  80.  
  81. }
  82. return 1;
  83. }
  84.  
  85. void unlock_n_threads_with_timeout(int id, int* local)
  86. {
  87. node* moj=local[0];
  88. if(moj->next!=NULL)
  89. {
  90. node* novi=moj->next;
  91. while(1)
  92. {
  93. if(!compare_and_set(&novi->flag,WAITING,UNLOCKED))
  94. {
  95. node* temp=novi;
  96. novi=novi->next;
  97. free(temp);
  98. }
  99. else
  100. {
  101. break;
  102. }
  103. }
  104. }
  105. else
  106. {
  107. if(!compare_and_set(&tail, moj,NULL))
  108. {
  109. while(moj->next==NULL)
  110. {
  111. sleep(0);
  112. }
  113. node *novi=moj->next;
  114. compare_and_set(&novi->flag,WAITING,UNLOCKED);
  115. }
  116. free(moj);
  117. }
  118. }
  119.  
  120. int main()
  121. {
  122. tail=NULL;
  123. start_timeout_mutex_n_threads_test();
  124. printf("MinDelta: %lf",minDelta);
  125. return 0;
  126. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement