lock.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #include "dat.h"
  2. #include "fns.h"
  3. #include "error.h"
  4. void
  5. lock(Lock *l)
  6. {
  7. int i;
  8. if(_tas(&l->val) == 0)
  9. return;
  10. for(i=0; i<100; i++){
  11. if(_tas(&l->val) == 0)
  12. return;
  13. osyield();
  14. }
  15. for(i=1;; i++){
  16. if(_tas(&l->val) == 0)
  17. return;
  18. osmillisleep(i*10);
  19. if(i > 100){
  20. osyield();
  21. i = 1;
  22. }
  23. }
  24. }
  25. int
  26. canlock(Lock *l)
  27. {
  28. return _tas(&l->val) == 0;
  29. }
  30. void
  31. unlock(Lock *l)
  32. {
  33. coherence();
  34. l->val = 0;
  35. }
  36. void
  37. qlock(QLock *q)
  38. {
  39. Proc *p;
  40. lock(&q->use);
  41. if(!q->locked) {
  42. q->locked = 1;
  43. unlock(&q->use);
  44. return;
  45. }
  46. p = q->tail;
  47. if(p == 0)
  48. q->head = up;
  49. else
  50. p->qnext = up;
  51. q->tail = up;
  52. up->qnext = 0;
  53. unlock(&q->use);
  54. osblock();
  55. }
  56. int
  57. canqlock(QLock *q)
  58. {
  59. if(!canlock(&q->use))
  60. return 0;
  61. if(q->locked){
  62. unlock(&q->use);
  63. return 0;
  64. }
  65. q->locked = 1;
  66. unlock(&q->use);
  67. return 1;
  68. }
  69. void
  70. qunlock(QLock *q)
  71. {
  72. Proc *p;
  73. lock(&q->use);
  74. p = q->head;
  75. if(p) {
  76. q->head = p->qnext;
  77. if(q->head == 0)
  78. q->tail = 0;
  79. unlock(&q->use);
  80. osready(p);
  81. return;
  82. }
  83. q->locked = 0;
  84. unlock(&q->use);
  85. }
  86. void
  87. rlock(RWlock *l)
  88. {
  89. qlock(&l->x); /* wait here for writers and exclusion */
  90. lock(&l->l);
  91. l->readers++;
  92. canqlock(&l->k); /* block writers if we are the first reader */
  93. unlock(&l->l);
  94. qunlock(&l->x);
  95. }
  96. /* same as rlock but punts if there are any writers waiting */
  97. int
  98. canrlock(RWlock *l)
  99. {
  100. if (!canqlock(&l->x))
  101. return 0;
  102. lock(&l->l);
  103. l->readers++;
  104. canqlock(&l->k); /* block writers if we are the first reader */
  105. unlock(&l->l);
  106. qunlock(&l->x);
  107. return 1;
  108. }
  109. void
  110. runlock(RWlock *l)
  111. {
  112. lock(&l->l);
  113. if(--l->readers == 0) /* last reader out allows writers */
  114. qunlock(&l->k);
  115. unlock(&l->l);
  116. }
  117. void
  118. wlock(RWlock *l)
  119. {
  120. qlock(&l->x); /* wait here for writers and exclusion */
  121. qlock(&l->k); /* wait here for last reader */
  122. }
  123. void
  124. wunlock(RWlock *l)
  125. {
  126. qunlock(&l->k);
  127. qunlock(&l->x);
  128. }