sync_linux.odin 963 B

12345678910111213141516171819202122232425262728293031
  1. package sync
  2. import "core:sys/unix"
  3. // The Darwin docs say it best:
  4. // A semaphore is much like a lock, except that a finite number of threads can hold it simultaneously.
  5. // Semaphores can be thought of as being much like piles of tokens; multiple threads can take these tokens,
  6. // but when there are none left, a thread must wait until another thread returns one.
  7. Semaphore :: struct #align 16 {
  8. handle: unix.sem_t,
  9. }
  10. semaphore_init :: proc(s: ^Semaphore, initial_count := 0) {
  11. assert(unix.sem_init(&s.handle, 0, u32(initial_count)) == 0);
  12. }
  13. semaphore_destroy :: proc(s: ^Semaphore) {
  14. assert(unix.sem_destroy(&s.handle) == 0);
  15. s.handle = {};
  16. }
  17. semaphore_post :: proc(s: ^Semaphore, count := 1) {
  18. // NOTE: SPEED: If there's one syscall to do this, we should use it instead of the loop.
  19. for in 0..count-1 {
  20. assert(unix.sem_post(&s.handle) == 0);
  21. }
  22. }
  23. semaphore_wait_for :: proc(s: ^Semaphore) {
  24. assert(unix.sem_wait(&s.handle) == 0);
  25. }