Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define UNLOCKED 0
  4. #define LOCKED 1
  5. #define TIMED_OUT 2
  6. typedef struct Node{
  7. int flag;
  8. struct Node * next;
  9. } Node;
  10.  
  11. Node* tail = NULL;
  12. int sucsses = NULL;
  13. double startID[80];
  14. double minTime = 10.0;
  15. double maxTime = 0.0;
  16.  
  17.  
  18. void init_MCSLock(){
  19.  
  20. }
  21.  
  22. int lock_n_threads_with_timeout(int id, int* local, int timeout)
  23. {
  24. double start = get_time();
  25. startID[id] = start;
  26. double wait = timeout/1000.0;
  27.  
  28. Node* node = (Node*) malloc(sizeof(Node));
  29. node->flag = UNLOCKED;
  30. node->next = NULL;
  31. *local = node;
  32.  
  33. Node* old = (Node*) get_and_set((int*)&tail, (int)node);
  34.  
  35. if(old != NULL){
  36.  
  37. node->flag = LOCKED;
  38. old->next = node;
  39. while (node->flag == LOCKED) {
  40. // printf("sleep1");
  41. // fflush(stdout);
  42. double end = get_time();
  43. double waitedTime = end - start;
  44.  
  45. if(waitedTime > wait){
  46. // printf("timedOut ");
  47. // fflush(stdout);
  48. node->flag = TIMED_OUT;
  49. return 0;
  50. }
  51. sleep(1);
  52. }
  53. node->flag = UNLOCKED;
  54. }
  55. // node->flag = UNLOCKED; // da li trebamo odvde da otkljucavamo?
  56. return 1;
  57.  
  58. }
  59. void unlock_n_threads_with_timeout(int id, int* local)
  60. {
  61. Node* node = (Node*) *local;
  62.  
  63.  
  64. if(node->next == NULL){
  65. sucsses = (Node*) compare_and_set((int*)&tail, (int)node, (int)NULL);
  66. if(sucsses){
  67. printf("sucsses ");
  68. fflush(stdout);
  69. }
  70. else{
  71. while(node->next == NULL){
  72. printf("sleep2");
  73. fflush(stdout);
  74. sleep(1);
  75. }
  76.  
  77. // node->next->flag = 0;
  78.  
  79. }
  80. } else{
  81. Node* nextNode = (Node*) node->next;
  82. if(nextNode->flag == TIMED_OUT){
  83. if(!(compare_and_set(&tail, nextNode, NULL))){
  84. nextNode = nextNode->next;
  85. printf("WTF? %d\n", id);
  86. fflush(stdout);
  87. }
  88. }else if (nextNode->flag == LOCKED){
  89. printf("LOCKED->UNLOCKED \n");
  90. fflush(stdout);
  91. nextNode->flag = UNLOCKED;
  92. nextNode = NULL;
  93. //free(node);
  94. }
  95. }
  96.  
  97.  
  98. double finalTime = get_time() - startID[id];
  99. if(finalTime > maxTime) maxTime = finalTime;
  100. if(finalTime < minTime) minTime = finalTime;
  101.  
  102. }
  103.  
  104. int main()
  105. {
  106.  
  107. start_timeout_mutex_n_threads_test();
  108. printf("MAX DELTA = %.5lf\n", maxTime);
  109. printf("MIN DELTA = %.5lf\n", minTime);
  110. return 0;
  111.  
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement