thread_pool.odin 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package thread
  2. /*
  3. thread.Pool
  4. Copyright 2022 eisbehr
  5. Made available under Odin's BSD-3 license.
  6. */
  7. import "base:intrinsics"
  8. import "core:sync"
  9. import "core:mem"
  10. Task_Proc :: #type proc(task: Task)
  11. Task :: struct {
  12. procedure: Task_Proc,
  13. data: rawptr,
  14. user_index: int,
  15. allocator: mem.Allocator,
  16. }
  17. // Do not access the pool's members directly while the pool threads are running,
  18. // since they use different kinds of locking and mutual exclusion devices.
  19. // Careless access can and will lead to nasty bugs. Once initialized, the
  20. // pool's memory address is not allowed to change until it is destroyed.
  21. Pool :: struct {
  22. allocator: mem.Allocator,
  23. mutex: sync.Mutex,
  24. sem_available: sync.Sema,
  25. // the following values are atomic
  26. num_waiting: int,
  27. num_in_processing: int,
  28. num_outstanding: int, // num_waiting + num_in_processing
  29. num_done: int,
  30. // end of atomics
  31. is_running: bool,
  32. threads: []^Thread,
  33. tasks: [dynamic]Task,
  34. tasks_done: [dynamic]Task,
  35. }
  36. Pool_Thread_Data :: struct {
  37. pool: ^Pool,
  38. task: Task,
  39. }
  40. @(private="file")
  41. pool_thread_runner :: proc(t: ^Thread) {
  42. data := cast(^Pool_Thread_Data)t.data
  43. pool := data.pool
  44. for intrinsics.atomic_load(&pool.is_running) {
  45. sync.wait(&pool.sem_available)
  46. if task, ok := pool_pop_waiting(pool); ok {
  47. data.task = task
  48. pool_do_work(pool, task)
  49. data.task = {}
  50. }
  51. }
  52. sync.post(&pool.sem_available, 1)
  53. }
  54. // Once initialized, the pool's memory address is not allowed to change until
  55. // it is destroyed.
  56. //
  57. // The thread pool requires an allocator which it either owns, or which is thread safe.
  58. pool_init :: proc(pool: ^Pool, allocator: mem.Allocator, thread_count: int) {
  59. context.allocator = allocator
  60. pool.allocator = allocator
  61. pool.tasks = make([dynamic]Task)
  62. pool.tasks_done = make([dynamic]Task)
  63. pool.threads = make([]^Thread, max(thread_count, 1))
  64. pool.is_running = true
  65. for _, i in pool.threads {
  66. t := create(pool_thread_runner)
  67. data := new(Pool_Thread_Data)
  68. data.pool = pool
  69. t.user_index = i
  70. t.data = data
  71. pool.threads[i] = t
  72. }
  73. }
  74. pool_destroy :: proc(pool: ^Pool) {
  75. delete(pool.tasks)
  76. delete(pool.tasks_done)
  77. for &t in pool.threads {
  78. data := cast(^Pool_Thread_Data)t.data
  79. free(data, pool.allocator)
  80. destroy(t)
  81. }
  82. delete(pool.threads, pool.allocator)
  83. }
  84. pool_start :: proc(pool: ^Pool) {
  85. for t in pool.threads {
  86. start(t)
  87. }
  88. }
  89. // Finish tasks that have already started processing, then shut down all pool
  90. // threads. Might leave over waiting tasks, any memory allocated for the
  91. // user data of those tasks will not be freed.
  92. pool_join :: proc(pool: ^Pool) {
  93. intrinsics.atomic_store(&pool.is_running, false)
  94. sync.post(&pool.sem_available, len(pool.threads))
  95. yield()
  96. started_count: int
  97. for started_count < len(pool.threads) {
  98. started_count = 0
  99. for t in pool.threads {
  100. if .Started in t.flags {
  101. started_count += 1
  102. if .Joined not_in t.flags {
  103. join(t)
  104. }
  105. }
  106. }
  107. }
  108. }
  109. // Add a task to the thread pool.
  110. //
  111. // Tasks can be added from any thread, not just the thread that created
  112. // the thread pool. You can even add tasks from inside other tasks.
  113. //
  114. // Each task also needs an allocator which it either owns, or which is thread
  115. // safe.
  116. pool_add_task :: proc(pool: ^Pool, allocator: mem.Allocator, procedure: Task_Proc, data: rawptr, user_index: int = 0) {
  117. sync.guard(&pool.mutex)
  118. append(&pool.tasks, Task{
  119. procedure = procedure,
  120. data = data,
  121. user_index = user_index,
  122. allocator = allocator,
  123. })
  124. intrinsics.atomic_add(&pool.num_waiting, 1)
  125. intrinsics.atomic_add(&pool.num_outstanding, 1)
  126. sync.post(&pool.sem_available, 1)
  127. }
  128. // Forcibly stop a running task by its user index.
  129. //
  130. // This will terminate the underlying thread. Ideally, you should use some
  131. // means of communication to stop a task, as thread termination may leave
  132. // resources unclaimed.
  133. //
  134. // The thread will be restarted to accept new tasks.
  135. //
  136. // Returns true if the task was found and terminated.
  137. pool_stop_task :: proc(pool: ^Pool, user_index: int, exit_code: int = 1) -> bool {
  138. sync.guard(&pool.mutex)
  139. for t, i in pool.threads {
  140. data := cast(^Pool_Thread_Data)t.data
  141. if data.task.user_index == user_index && data.task.procedure != nil {
  142. terminate(t, exit_code)
  143. append(&pool.tasks_done, data.task)
  144. intrinsics.atomic_add(&pool.num_done, 1)
  145. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  146. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  147. destroy(t)
  148. replacement := create(pool_thread_runner)
  149. replacement.user_index = t.user_index
  150. replacement.data = data
  151. data.task = {}
  152. pool.threads[i] = replacement
  153. start(replacement)
  154. return true
  155. }
  156. }
  157. return false
  158. }
  159. // Forcibly stop all running tasks.
  160. //
  161. // The same notes from `pool_stop_task` apply here.
  162. pool_stop_all_tasks :: proc(pool: ^Pool, exit_code: int = 1) {
  163. sync.guard(&pool.mutex)
  164. for t, i in pool.threads {
  165. data := cast(^Pool_Thread_Data)t.data
  166. if data.task.procedure != nil {
  167. terminate(t, exit_code)
  168. append(&pool.tasks_done, data.task)
  169. intrinsics.atomic_add(&pool.num_done, 1)
  170. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  171. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  172. destroy(t)
  173. replacement := create(pool_thread_runner)
  174. replacement.user_index = t.user_index
  175. replacement.data = data
  176. data.task = {}
  177. pool.threads[i] = replacement
  178. start(replacement)
  179. }
  180. }
  181. }
  182. // Force the pool to stop all of its threads and put it into a state where
  183. // it will no longer run any more tasks.
  184. //
  185. // The pool must still be destroyed after this.
  186. pool_shutdown :: proc(pool: ^Pool, exit_code: int = 1) {
  187. intrinsics.atomic_store(&pool.is_running, false)
  188. sync.guard(&pool.mutex)
  189. for t in pool.threads {
  190. terminate(t, exit_code)
  191. data := cast(^Pool_Thread_Data)t.data
  192. if data.task.procedure != nil {
  193. append(&pool.tasks_done, data.task)
  194. intrinsics.atomic_add(&pool.num_done, 1)
  195. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  196. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  197. }
  198. }
  199. }
  200. // Number of tasks waiting to be processed. Only informational, mostly for
  201. // debugging. Don't rely on this value being consistent with other num_*
  202. // values.
  203. pool_num_waiting :: #force_inline proc(pool: ^Pool) -> int {
  204. return intrinsics.atomic_load(&pool.num_waiting)
  205. }
  206. // Number of tasks currently being processed. Only informational, mostly for
  207. // debugging. Don't rely on this value being consistent with other num_*
  208. // values.
  209. pool_num_in_processing :: #force_inline proc(pool: ^Pool) -> int {
  210. return intrinsics.atomic_load(&pool.num_in_processing)
  211. }
  212. // Outstanding tasks are all tasks that are not done, that is, tasks that are
  213. // waiting, as well as tasks that are currently being processed. Only
  214. // informational, mostly for debugging. Don't rely on this value being
  215. // consistent with other num_* values.
  216. pool_num_outstanding :: #force_inline proc(pool: ^Pool) -> int {
  217. return intrinsics.atomic_load(&pool.num_outstanding)
  218. }
  219. // Number of tasks which are done processing. Only informational, mostly for
  220. // debugging. Don't rely on this value being consistent with other num_*
  221. // values.
  222. pool_num_done :: #force_inline proc(pool: ^Pool) -> int {
  223. return intrinsics.atomic_load(&pool.num_done)
  224. }
  225. // If tasks are only being added from one thread, and this procedure is being
  226. // called from that same thread, it will reliably tell if the thread pool is
  227. // empty or not. Empty in this case means there are no tasks waiting, being
  228. // processed, or _done_.
  229. pool_is_empty :: #force_inline proc(pool: ^Pool) -> bool {
  230. return pool_num_outstanding(pool) == 0 && pool_num_done(pool) == 0
  231. }
  232. // Mostly for internal use.
  233. pool_pop_waiting :: proc(pool: ^Pool) -> (task: Task, got_task: bool) {
  234. sync.guard(&pool.mutex)
  235. if len(pool.tasks) != 0 {
  236. intrinsics.atomic_sub(&pool.num_waiting, 1)
  237. intrinsics.atomic_add(&pool.num_in_processing, 1)
  238. task = pop_front(&pool.tasks)
  239. got_task = true
  240. }
  241. return
  242. }
  243. // Use this to take out finished tasks.
  244. pool_pop_done :: proc(pool: ^Pool) -> (task: Task, got_task: bool) {
  245. sync.guard(&pool.mutex)
  246. if len(pool.tasks_done) != 0 {
  247. task = pop_front(&pool.tasks_done)
  248. got_task = true
  249. intrinsics.atomic_sub(&pool.num_done, 1)
  250. }
  251. return
  252. }
  253. // Mostly for internal use.
  254. pool_do_work :: proc(pool: ^Pool, task: Task) {
  255. {
  256. context.allocator = task.allocator
  257. task.procedure(task)
  258. }
  259. sync.guard(&pool.mutex)
  260. append(&pool.tasks_done, task)
  261. intrinsics.atomic_add(&pool.num_done, 1)
  262. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  263. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  264. }
  265. // Process the rest of the tasks, also use this thread for processing, then join
  266. // all the pool threads.
  267. pool_finish :: proc(pool: ^Pool) {
  268. for task in pool_pop_waiting(pool) {
  269. pool_do_work(pool, task)
  270. }
  271. pool_join(pool)
  272. }