《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
681 B

10 years ago
  1. #ifndef __USER_LIBS_LOCK_H__
  2. #define __USER_LIBS_LOCK_H__
  3. #include <defs.h>
  4. #include <atomic.h>
  5. #include <ulib.h>
  6. #define INIT_LOCK {0}
  7. typedef volatile bool lock_t;
  8. static inline void
  9. lock_init(lock_t *l) {
  10. *l = 0;
  11. }
  12. static inline bool
  13. try_lock(lock_t *l) {
  14. return test_and_set_bit(0, l);
  15. }
  16. static inline void
  17. lock(lock_t *l) {
  18. if (try_lock(l)) {
  19. int step = 0;
  20. do {
  21. yield();
  22. if (++ step == 100) {
  23. step = 0;
  24. sleep(10);
  25. }
  26. } while (try_lock(l));
  27. }
  28. }
  29. static inline void
  30. unlock(lock_t *l) {
  31. test_and_clear_bit(0, l);
  32. }
  33. #endif /* !__USER_LIBS_LOCK_H__ */