sync_windows.odin 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package sync
  2. import "core:sys/win32"
  3. import "core:atomics"
  4. Semaphore :: struct {
  5. _handle: win32.Handle,
  6. }
  7. Mutex :: struct {
  8. _critical_section: win32.Critical_Section,
  9. }
  10. Condition :: struct {
  11. event: win32.Handle,
  12. }
  13. current_thread_id :: proc() -> i32 {
  14. return i32(win32.get_current_thread_id());
  15. }
  16. semaphore_init :: proc(s: ^Semaphore) {
  17. s._handle = win32.create_semaphore_a(nil, 0, 1<<31-1, nil);
  18. }
  19. semaphore_destroy :: proc(s: ^Semaphore) {
  20. win32.close_handle(s._handle);
  21. }
  22. semaphore_post :: proc(s: ^Semaphore, count: int) {
  23. win32.release_semaphore(s._handle, i32(count), nil);
  24. }
  25. semaphore_release :: inline proc(s: ^Semaphore) {
  26. semaphore_post(s, 1);
  27. }
  28. semaphore_wait :: proc(s: ^Semaphore) {
  29. result := win32.wait_for_single_object(s._handle, win32.INFINITE);
  30. assert(result != win32.WAIT_FAILED);
  31. }
  32. mutex_init :: proc(m: ^Mutex, spin_count := 0) {
  33. win32.initialize_critical_section_and_spin_count(&m._critical_section, u32(spin_count));
  34. }
  35. mutex_destroy :: proc(m: ^Mutex) {
  36. win32.delete_critical_section(&m._critical_section);
  37. }
  38. mutex_lock :: proc(m: ^Mutex) {
  39. win32.enter_critical_section(&m._critical_section);
  40. }
  41. mutex_try_lock :: proc(m: ^Mutex) -> bool {
  42. return bool(win32.try_enter_critical_section(&m._critical_section));
  43. }
  44. mutex_unlock :: proc(m: ^Mutex) {
  45. win32.leave_critical_section(&m._critical_section);
  46. }
  47. condition_init :: proc(using c: ^Condition) {
  48. event = win32.create_event_a(nil, false, false, nil);
  49. assert(event != nil);
  50. }
  51. condition_signal :: proc(using c: ^Condition) {
  52. ok := win32.set_event(event);
  53. assert(bool(ok));
  54. }
  55. condition_wait_for :: proc(using c: ^Condition) {
  56. result := win32.wait_for_single_object(event, win32.INFINITE);
  57. assert(result != win32.WAIT_FAILED);
  58. }
  59. condition_destroy :: proc(using c: ^Condition) {
  60. if event != nil {
  61. win32.close_handle(event);
  62. }
  63. }