lock.c 493 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <u.h>
  2. #include <libc.h>
  3. void
  4. lock(Lock *lk)
  5. {
  6. int i;
  7. /* once fast */
  8. if(!_tas(&lk->val))
  9. return;
  10. /* a thousand times pretty fast */
  11. for(i=0; i<1000; i++){
  12. if(!_tas(&lk->val))
  13. return;
  14. sleep(0);
  15. }
  16. /* now nice and slow */
  17. for(i=0; i<1000; i++){
  18. if(!_tas(&lk->val))
  19. return;
  20. sleep(100);
  21. }
  22. /* take your time */
  23. while(_tas(&lk->val))
  24. sleep(1000);
  25. }
  26. int
  27. canlock(Lock *lk)
  28. {
  29. if(_tas(&lk->val))
  30. return 0;
  31. return 1;
  32. }
  33. void
  34. unlock(Lock *lk)
  35. {
  36. lk->val = 0;
  37. }