DESIGN-sem.txt 789 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. Semaphores pseudocode
  2. ==============================
  3. int sem_wait(sem_t * sem);
  4. int sem_trywait(sem_t * sem);
  5. int sem_post(sem_t * sem);
  6. int sem_getvalue(sem_t * sem, int * sval);
  7. struct sem_t {
  8. unsigned int count;
  9. - current semaphore count, also used as a futex
  10. }
  11. sem_wait(sem_t *sem)
  12. {
  13. for (;;) {
  14. if (atomic_decrement_if_positive(sem->count))
  15. break;
  16. futex_wait(&sem->count, 0)
  17. }
  18. }
  19. sem_post(sem_t *sem)
  20. {
  21. n = atomic_increment(sem->count);
  22. // Pass the new value of sem->count
  23. futex_wake(&sem->count, n + 1);
  24. }
  25. sem_trywait(sem_t *sem)
  26. {
  27. if (atomic_decrement_if_positive(sem->count)) {
  28. return 0;
  29. } else {
  30. return EAGAIN;
  31. }
  32. }
  33. sem_getvalue(sem_t *sem, int *sval)
  34. {
  35. *sval = sem->count;
  36. read_barrier();
  37. }