sync_linux.odin 1.0 KB

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