thread_unix.odin 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // +build linux, darwin, freebsd, openbsd, netbsd, haiku
  2. // +private
  3. package thread
  4. import "base:runtime"
  5. import "core:sync"
  6. import "core:sys/unix"
  7. import "core:time"
  8. _IS_SUPPORTED :: true
  9. CAS :: sync.atomic_compare_exchange_strong
  10. // NOTE(tetra): Aligned here because of core/unix/pthread_linux.odin/pthread_t.
  11. // Also see core/sys/darwin/mach_darwin.odin/semaphore_t.
  12. Thread_Os_Specific :: struct #align(16) {
  13. unix_thread: unix.pthread_t, // NOTE: very large on Darwin, small on Linux.
  14. cond: sync.Cond,
  15. mutex: sync.Mutex,
  16. }
  17. //
  18. // Creates a thread which will run the given procedure.
  19. // It then waits for `start` to be called.
  20. //
  21. _create :: proc(procedure: Thread_Proc, priority: Thread_Priority) -> ^Thread {
  22. __unix_thread_entry_proc :: proc "c" (t: rawptr) -> rawptr {
  23. t := (^Thread)(t)
  24. // We need to give the thread a moment to start up before we enable cancellation.
  25. can_set_thread_cancel_state := unix.pthread_setcancelstate(unix.PTHREAD_CANCEL_ENABLE, nil) == 0
  26. sync.lock(&t.mutex)
  27. t.id = sync.current_thread_id()
  28. for (.Started not_in sync.atomic_load(&t.flags)) {
  29. // HACK: use a timeout so in the event that the condition is signalled at THIS comment's exact point
  30. // (after checking flags, before starting the wait) it gets itself out of that deadlock after a ms.
  31. sync.wait_with_timeout(&t.cond, &t.mutex, time.Millisecond)
  32. }
  33. if .Joined in sync.atomic_load(&t.flags) {
  34. return nil
  35. }
  36. // Enable thread's cancelability.
  37. if can_set_thread_cancel_state {
  38. unix.pthread_setcanceltype (unix.PTHREAD_CANCEL_ASYNCHRONOUS, nil)
  39. unix.pthread_setcancelstate(unix.PTHREAD_CANCEL_ENABLE, nil)
  40. }
  41. {
  42. init_context := t.init_context
  43. // NOTE(tetra, 2023-05-31): Must do this AFTER thread.start() is called, so that the user can set the init_context, etc!
  44. // Here on Unix, we start the OS thread in a running state, and so we manually have it wait on a condition
  45. // variable above. We must perform that waiting BEFORE we select the context!
  46. context = _select_context_for_thread(init_context)
  47. defer {
  48. _maybe_destroy_default_temp_allocator(init_context)
  49. runtime.run_thread_local_cleaners()
  50. }
  51. t.procedure(t)
  52. }
  53. sync.atomic_or(&t.flags, { .Done })
  54. sync.unlock(&t.mutex)
  55. if .Self_Cleanup in sync.atomic_load(&t.flags) {
  56. res := unix.pthread_detach(t.unix_thread)
  57. assert_contextless(res == 0)
  58. t.unix_thread = {}
  59. // NOTE(ftphikari): It doesn't matter which context 'free' received, right?
  60. context = {}
  61. free(t, t.creation_allocator)
  62. }
  63. return nil
  64. }
  65. attrs: unix.pthread_attr_t
  66. if unix.pthread_attr_init(&attrs) != 0 {
  67. return nil // NOTE(tetra, 2019-11-01): POSIX OOM.
  68. }
  69. defer unix.pthread_attr_destroy(&attrs)
  70. // NOTE(tetra, 2019-11-01): These only fail if their argument is invalid.
  71. res: i32
  72. res = unix.pthread_attr_setdetachstate(&attrs, unix.PTHREAD_CREATE_JOINABLE)
  73. assert(res == 0)
  74. when ODIN_OS != .Haiku && ODIN_OS != .NetBSD {
  75. res = unix.pthread_attr_setinheritsched(&attrs, unix.PTHREAD_EXPLICIT_SCHED)
  76. assert(res == 0)
  77. }
  78. thread := new(Thread)
  79. if thread == nil {
  80. return nil
  81. }
  82. thread.creation_allocator = context.allocator
  83. // Set thread priority.
  84. policy: i32
  85. when ODIN_OS != .Haiku && ODIN_OS != .NetBSD {
  86. res = unix.pthread_attr_getschedpolicy(&attrs, &policy)
  87. assert(res == 0)
  88. }
  89. params: unix.sched_param
  90. res = unix.pthread_attr_getschedparam(&attrs, &params)
  91. assert(res == 0)
  92. low := unix.sched_get_priority_min(policy)
  93. high := unix.sched_get_priority_max(policy)
  94. switch priority {
  95. case .Normal: // Okay
  96. case .Low: params.sched_priority = low + 1
  97. case .High: params.sched_priority = high
  98. }
  99. res = unix.pthread_attr_setschedparam(&attrs, &params)
  100. assert(res == 0)
  101. thread.procedure = procedure
  102. if unix.pthread_create(&thread.unix_thread, &attrs, __unix_thread_entry_proc, thread) != 0 {
  103. free(thread, thread.creation_allocator)
  104. return nil
  105. }
  106. return thread
  107. }
  108. _start :: proc(t: ^Thread) {
  109. sync.atomic_or(&t.flags, { .Started })
  110. sync.signal(&t.cond)
  111. }
  112. _is_done :: proc(t: ^Thread) -> bool {
  113. return .Done in sync.atomic_load(&t.flags)
  114. }
  115. _join :: proc(t: ^Thread) {
  116. // sync.guard(&t.mutex)
  117. if unix.pthread_equal(unix.pthread_self(), t.unix_thread) {
  118. return
  119. }
  120. // Preserve other flags besides `.Joined`, like `.Started`.
  121. unjoined := sync.atomic_load(&t.flags) - {.Joined}
  122. joined := unjoined + {.Joined}
  123. // Try to set `t.flags` from unjoined to joined. If it returns joined,
  124. // it means the previous value had that flag set and we can return.
  125. if res, ok := CAS(&t.flags, unjoined, joined); res == joined && !ok {
  126. return
  127. }
  128. // Prevent non-started threads from blocking main thread with initial wait
  129. // condition.
  130. if .Started not_in unjoined {
  131. _start(t)
  132. }
  133. unix.pthread_join(t.unix_thread, nil)
  134. }
  135. _join_multiple :: proc(threads: ..^Thread) {
  136. for t in threads {
  137. _join(t)
  138. }
  139. }
  140. _destroy :: proc(t: ^Thread) {
  141. _join(t)
  142. t.unix_thread = {}
  143. free(t, t.creation_allocator)
  144. }
  145. _terminate :: proc(t: ^Thread, exit_code: int) {
  146. // NOTE(Feoramund): For thread cancellation to succeed on BSDs and
  147. // possibly Darwin systems, the thread must call one of the pthread
  148. // cancelation points at some point after this.
  149. //
  150. // The most obvious one of these is `pthread_cancel`, but there is an
  151. // entire list of functions that act as cancelation points available in the
  152. // pthreads manual page.
  153. //
  154. // This is in contrast to behavior I have seen on Linux where the thread is
  155. // just terminated.
  156. unix.pthread_cancel(t.unix_thread)
  157. }
  158. _yield :: proc() {
  159. unix.sched_yield()
  160. }