thread_unix.odin 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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/posix"
  7. _IS_SUPPORTED :: true
  8. // NOTE(tetra): Aligned here because of core/unix/pthread_linux.odin/pthread_t.
  9. // Also see core/sys/darwin/mach_darwin.odin/semaphore_t.
  10. Thread_Os_Specific :: struct #align(16) {
  11. unix_thread: posix.pthread_t, // NOTE: very large on Darwin, small on Linux.
  12. start_ok: sync.Sema,
  13. }
  14. //
  15. // Creates a thread which will run the given procedure.
  16. // It then waits for `start` to be called.
  17. //
  18. _create :: proc(procedure: Thread_Proc, priority: Thread_Priority) -> ^Thread {
  19. __unix_thread_entry_proc :: proc "c" (t: rawptr) -> rawptr {
  20. t := (^Thread)(t)
  21. // We need to give the thread a moment to start up before we enable cancellation.
  22. // NOTE(laytan): setting to .DISABLE on darwin, with .ENABLE pthread_cancel would deadlock
  23. // most of the time, don't ask me why.
  24. can_set_thread_cancel_state := posix.pthread_setcancelstate(.DISABLE when ODIN_OS == .Darwin else .ENABLE, nil) == nil
  25. t.id = sync.current_thread_id()
  26. if .Started not_in sync.atomic_load(&t.flags) {
  27. sync.wait(&t.start_ok)
  28. }
  29. if .Joined in sync.atomic_load(&t.flags) {
  30. return nil
  31. }
  32. // Enable thread's cancelability.
  33. // NOTE(laytan): Darwin does not correctly/fully support all of this, not doing this does
  34. // actually make pthread_cancel work in the capacity of my tests, while executing this would
  35. // basically always make it deadlock.
  36. if ODIN_OS != .Darwin && can_set_thread_cancel_state {
  37. err := posix.pthread_setcancelstate(.ENABLE, nil)
  38. assert_contextless(err == nil)
  39. err = posix.pthread_setcanceltype(.ASYNCHRONOUS, nil)
  40. assert_contextless(err == nil)
  41. }
  42. {
  43. init_context := t.init_context
  44. // NOTE(tetra, 2023-05-31): Must do this AFTER thread.start() is called, so that the user can set the init_context, etc!
  45. // Here on Unix, we start the OS thread in a running state, and so we manually have it wait on a condition
  46. // variable above. We must perform that waiting BEFORE we select the context!
  47. context = _select_context_for_thread(init_context)
  48. defer {
  49. _maybe_destroy_default_temp_allocator(init_context)
  50. runtime.run_thread_local_cleaners()
  51. }
  52. t.procedure(t)
  53. }
  54. sync.atomic_or(&t.flags, { .Done })
  55. if .Self_Cleanup in sync.atomic_load(&t.flags) {
  56. res := posix.pthread_detach(t.unix_thread)
  57. assert_contextless(res == nil)
  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: posix.pthread_attr_t
  66. if posix.pthread_attr_init(&attrs) != nil {
  67. return nil // NOTE(tetra, 2019-11-01): POSIX OOM.
  68. }
  69. defer posix.pthread_attr_destroy(&attrs)
  70. // NOTE(tetra, 2019-11-01): These only fail if their argument is invalid.
  71. res: posix.Errno
  72. res = posix.pthread_attr_setdetachstate(&attrs, .CREATE_JOINABLE)
  73. assert(res == nil)
  74. when ODIN_OS != .Haiku && ODIN_OS != .NetBSD {
  75. res = posix.pthread_attr_setinheritsched(&attrs, .EXPLICIT_SCHED)
  76. assert(res == nil)
  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: posix.Sched_Policy
  85. when ODIN_OS != .Haiku && ODIN_OS != .NetBSD {
  86. res = posix.pthread_attr_getschedpolicy(&attrs, &policy)
  87. assert(res == nil)
  88. }
  89. params: posix.sched_param
  90. res = posix.pthread_attr_getschedparam(&attrs, &params)
  91. assert(res == nil)
  92. low := posix.sched_get_priority_min(policy)
  93. high := posix.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 = posix.pthread_attr_setschedparam(&attrs, &params)
  100. assert(res == nil)
  101. thread.procedure = procedure
  102. if posix.pthread_create(&thread.unix_thread, &attrs, __unix_thread_entry_proc, thread) != nil {
  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.post(&t.start_ok)
  111. }
  112. _is_done :: proc(t: ^Thread) -> bool {
  113. return .Done in sync.atomic_load(&t.flags)
  114. }
  115. _join :: proc(t: ^Thread) {
  116. if posix.pthread_equal(posix.pthread_self(), t.unix_thread) {
  117. return
  118. }
  119. // If the previous value was already `Joined`, then we can return.
  120. if .Joined in sync.atomic_or(&t.flags, {.Joined}) {
  121. return
  122. }
  123. // Prevent non-started threads from blocking main thread with initial wait
  124. // condition.
  125. if .Started not_in sync.atomic_load(&t.flags) {
  126. _start(t)
  127. }
  128. posix.pthread_join(t.unix_thread, nil)
  129. }
  130. _join_multiple :: proc(threads: ..^Thread) {
  131. for t in threads {
  132. _join(t)
  133. }
  134. }
  135. _destroy :: proc(t: ^Thread) {
  136. _join(t)
  137. t.unix_thread = {}
  138. free(t, t.creation_allocator)
  139. }
  140. _terminate :: proc(t: ^Thread, exit_code: int) {
  141. // NOTE(Feoramund): For thread cancellation to succeed on BSDs and
  142. // possibly Darwin systems, the thread must call one of the pthread
  143. // cancelation points at some point after this.
  144. //
  145. // The most obvious one of these is `pthread_cancel`, but there is an
  146. // entire list of functions that act as cancelation points available in the
  147. // pthreads manual page.
  148. //
  149. // This is in contrast to behavior I have seen on Linux where the thread is
  150. // just terminated.
  151. posix.pthread_cancel(t.unix_thread)
  152. }
  153. _yield :: proc() {
  154. posix.sched_yield()
  155. }