sync_windows.odin 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import (
  2. win32 "sys/windows.odin" when ODIN_OS == "windows";
  3. "atomics.odin";
  4. )
  5. type Semaphore struct {
  6. _handle: win32.Handle,
  7. }
  8. type Mutex struct {
  9. _semaphore: Semaphore,
  10. _counter: i32,
  11. _owner: i32,
  12. _recursion: i32,
  13. }
  14. proc current_thread_id() -> i32 {
  15. return i32(win32.get_current_thread_id());
  16. }
  17. proc semaphore_init(s: ^Semaphore) {
  18. s._handle = win32.create_semaphore_a(nil, 0, 1<<31-1, nil);
  19. }
  20. proc semaphore_destroy(s: ^Semaphore) {
  21. win32.close_handle(s._handle);
  22. }
  23. proc semaphore_post(s: ^Semaphore, count: int) {
  24. win32.release_semaphore(s._handle, i32(count), nil);
  25. }
  26. proc semaphore_release(s: ^Semaphore) #inline { semaphore_post(s, 1); }
  27. proc semaphore_wait(s: ^Semaphore) {
  28. win32.wait_for_single_object(s._handle, win32.INFINITE);
  29. }
  30. proc mutex_init(m: ^Mutex) {
  31. atomics.store(&m._counter, 0);
  32. atomics.store(&m._owner, current_thread_id());
  33. semaphore_init(&m._semaphore);
  34. m._recursion = 0;
  35. }
  36. proc mutex_destroy(m: ^Mutex) {
  37. semaphore_destroy(&m._semaphore);
  38. }
  39. proc mutex_lock(m: ^Mutex) {
  40. var thread_id = current_thread_id();
  41. if atomics.fetch_add(&m._counter, 1) > 0 {
  42. if thread_id != atomics.load(&m._owner) {
  43. semaphore_wait(&m._semaphore);
  44. }
  45. }
  46. atomics.store(&m._owner, thread_id);
  47. m._recursion++;
  48. }
  49. proc mutex_try_lock(m: ^Mutex) -> bool {
  50. var thread_id = current_thread_id();
  51. if atomics.load(&m._owner) == thread_id {
  52. atomics.fetch_add(&m._counter, 1);
  53. } else {
  54. var expected: i32 = 0;
  55. if atomics.load(&m._counter) != 0 {
  56. return false;
  57. }
  58. if atomics.compare_exchange(&m._counter, expected, 1) == 0 {
  59. return false;
  60. }
  61. atomics.store(&m._owner, thread_id);
  62. }
  63. m._recursion++;
  64. return true;
  65. }
  66. proc mutex_unlock(m: ^Mutex) {
  67. var recursion: i32;
  68. var thread_id = current_thread_id();
  69. assert(thread_id == atomics.load(&m._owner));
  70. m._recursion--;
  71. recursion = m._recursion;
  72. if recursion == 0 {
  73. atomics.store(&m._owner, thread_id);
  74. }
  75. if atomics.fetch_add(&m._counter, -1) > 1 {
  76. if recursion == 0 {
  77. semaphore_release(&m._semaphore);
  78. }
  79. }
  80. }