lock.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. l->val = 0;
  34. }
  35. void
  36. qlock(QLock *q)
  37. {
  38. Proc *p;
  39. lock(&q->use);
  40. if(!q->locked) {
  41. q->locked = 1;
  42. unlock(&q->use);
  43. return;
  44. }
  45. p = q->tail;
  46. if(p == 0)
  47. q->head = up;
  48. else
  49. p->qnext = up;
  50. q->tail = up;
  51. up->qnext = 0;
  52. unlock(&q->use);
  53. osblock();
  54. }
  55. int
  56. canqlock(QLock *q)
  57. {
  58. if(!canlock(&q->use))
  59. return 0;
  60. if(q->locked){
  61. unlock(&q->use);
  62. return 0;
  63. }
  64. q->locked = 1;
  65. unlock(&q->use);
  66. return 1;
  67. }
  68. void
  69. qunlock(QLock *q)
  70. {
  71. Proc *p;
  72. lock(&q->use);
  73. p = q->head;
  74. if(p) {
  75. q->head = p->qnext;
  76. if(q->head == 0)
  77. q->tail = 0;
  78. unlock(&q->use);
  79. osready(p);
  80. return;
  81. }
  82. q->locked = 0;
  83. unlock(&q->use);
  84. }
  85. void
  86. rlock(RWlock *l)
  87. {
  88. qlock(&l->x); /* wait here for writers and exclusion */
  89. lock(&l->l);
  90. l->readers++;
  91. canqlock(&l->k); /* block writers if we are the first reader */
  92. unlock(&l->l);
  93. qunlock(&l->x);
  94. }
  95. /* same as rlock but punts if there are any writers waiting */
  96. int
  97. canrlock(RWlock *l)
  98. {
  99. if (!canqlock(&l->x))
  100. return 0;
  101. lock(&l->l);
  102. l->readers++;
  103. canqlock(&l->k); /* block writers if we are the first reader */
  104. unlock(&l->l);
  105. qunlock(&l->x);
  106. return 1;
  107. }
  108. void
  109. runlock(RWlock *l)
  110. {
  111. lock(&l->l);
  112. if(--l->readers == 0) /* last reader out allows writers */
  113. qunlock(&l->k);
  114. unlock(&l->l);
  115. }
  116. void
  117. wlock(RWlock *l)
  118. {
  119. qlock(&l->x); /* wait here for writers and exclusion */
  120. qlock(&l->k); /* wait here for last reader */
  121. }
  122. void
  123. wunlock(RWlock *l)
  124. {
  125. qunlock(&l->k);
  126. qunlock(&l->x);
  127. }