thread_pool.odin 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. flags := intrinsics.atomic_load(&t.flags)
  101. if .Started in flags {
  102. started_count += 1
  103. if .Joined not_in flags {
  104. join(t)
  105. }
  106. }
  107. }
  108. }
  109. }
  110. // Add a task to the thread pool.
  111. //
  112. // Tasks can be added from any thread, not just the thread that created
  113. // the thread pool. You can even add tasks from inside other tasks.
  114. //
  115. // Each task also needs an allocator which it either owns, or which is thread
  116. // safe.
  117. pool_add_task :: proc(pool: ^Pool, allocator: mem.Allocator, procedure: Task_Proc, data: rawptr, user_index: int = 0) {
  118. sync.guard(&pool.mutex)
  119. append(&pool.tasks, Task{
  120. procedure = procedure,
  121. data = data,
  122. user_index = user_index,
  123. allocator = allocator,
  124. })
  125. intrinsics.atomic_add(&pool.num_waiting, 1)
  126. intrinsics.atomic_add(&pool.num_outstanding, 1)
  127. sync.post(&pool.sem_available, 1)
  128. }
  129. // Forcibly stop a running task by its user index.
  130. //
  131. // This will terminate the underlying thread. Ideally, you should use some
  132. // means of communication to stop a task, as thread termination may leave
  133. // resources unclaimed.
  134. //
  135. // The thread will be restarted to accept new tasks.
  136. //
  137. // Returns true if the task was found and terminated.
  138. pool_stop_task :: proc(pool: ^Pool, user_index: int, exit_code: int = 1) -> bool {
  139. sync.guard(&pool.mutex)
  140. for t, i in pool.threads {
  141. data := cast(^Pool_Thread_Data)t.data
  142. if data.task.user_index == user_index && data.task.procedure != nil {
  143. terminate(t, exit_code)
  144. append(&pool.tasks_done, data.task)
  145. intrinsics.atomic_add(&pool.num_done, 1)
  146. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  147. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  148. old_thread_user_index := t.user_index
  149. destroy(t)
  150. replacement := create(pool_thread_runner)
  151. replacement.user_index = old_thread_user_index
  152. replacement.data = data
  153. data.task = {}
  154. pool.threads[i] = replacement
  155. start(replacement)
  156. return true
  157. }
  158. }
  159. return false
  160. }
  161. // Forcibly stop all running tasks.
  162. //
  163. // The same notes from `pool_stop_task` apply here.
  164. pool_stop_all_tasks :: proc(pool: ^Pool, exit_code: int = 1) {
  165. sync.guard(&pool.mutex)
  166. for t, i in pool.threads {
  167. data := cast(^Pool_Thread_Data)t.data
  168. if data.task.procedure != nil {
  169. terminate(t, exit_code)
  170. append(&pool.tasks_done, data.task)
  171. intrinsics.atomic_add(&pool.num_done, 1)
  172. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  173. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  174. old_thread_user_index := t.user_index
  175. destroy(t)
  176. replacement := create(pool_thread_runner)
  177. replacement.user_index = old_thread_user_index
  178. replacement.data = data
  179. data.task = {}
  180. pool.threads[i] = replacement
  181. start(replacement)
  182. }
  183. }
  184. }
  185. // Force the pool to stop all of its threads and put it into a state where
  186. // it will no longer run any more tasks.
  187. //
  188. // The pool must still be destroyed after this.
  189. pool_shutdown :: proc(pool: ^Pool, exit_code: int = 1) {
  190. intrinsics.atomic_store(&pool.is_running, false)
  191. sync.guard(&pool.mutex)
  192. for t in pool.threads {
  193. terminate(t, exit_code)
  194. data := cast(^Pool_Thread_Data)t.data
  195. if data.task.procedure != nil {
  196. append(&pool.tasks_done, data.task)
  197. intrinsics.atomic_add(&pool.num_done, 1)
  198. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  199. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  200. }
  201. }
  202. }
  203. // Number of tasks waiting to be processed. Only informational, mostly for
  204. // debugging. Don't rely on this value being consistent with other num_*
  205. // values.
  206. pool_num_waiting :: #force_inline proc(pool: ^Pool) -> int {
  207. return intrinsics.atomic_load(&pool.num_waiting)
  208. }
  209. // Number of tasks currently being processed. Only informational, mostly for
  210. // debugging. Don't rely on this value being consistent with other num_*
  211. // values.
  212. pool_num_in_processing :: #force_inline proc(pool: ^Pool) -> int {
  213. return intrinsics.atomic_load(&pool.num_in_processing)
  214. }
  215. // Outstanding tasks are all tasks that are not done, that is, tasks that are
  216. // waiting, as well as tasks that are currently being processed. Only
  217. // informational, mostly for debugging. Don't rely on this value being
  218. // consistent with other num_* values.
  219. pool_num_outstanding :: #force_inline proc(pool: ^Pool) -> int {
  220. return intrinsics.atomic_load(&pool.num_outstanding)
  221. }
  222. // Number of tasks which are done processing. Only informational, mostly for
  223. // debugging. Don't rely on this value being consistent with other num_*
  224. // values.
  225. pool_num_done :: #force_inline proc(pool: ^Pool) -> int {
  226. return intrinsics.atomic_load(&pool.num_done)
  227. }
  228. // If tasks are only being added from one thread, and this procedure is being
  229. // called from that same thread, it will reliably tell if the thread pool is
  230. // empty or not. Empty in this case means there are no tasks waiting, being
  231. // processed, or _done_.
  232. pool_is_empty :: #force_inline proc(pool: ^Pool) -> bool {
  233. return pool_num_outstanding(pool) == 0 && pool_num_done(pool) == 0
  234. }
  235. // Mostly for internal use.
  236. pool_pop_waiting :: proc(pool: ^Pool) -> (task: Task, got_task: bool) {
  237. sync.guard(&pool.mutex)
  238. if len(pool.tasks) != 0 {
  239. intrinsics.atomic_sub(&pool.num_waiting, 1)
  240. intrinsics.atomic_add(&pool.num_in_processing, 1)
  241. task = pop_front(&pool.tasks)
  242. got_task = true
  243. }
  244. return
  245. }
  246. // Use this to take out finished tasks.
  247. pool_pop_done :: proc(pool: ^Pool) -> (task: Task, got_task: bool) {
  248. sync.guard(&pool.mutex)
  249. if len(pool.tasks_done) != 0 {
  250. task = pop_front(&pool.tasks_done)
  251. got_task = true
  252. intrinsics.atomic_sub(&pool.num_done, 1)
  253. }
  254. return
  255. }
  256. // Mostly for internal use.
  257. pool_do_work :: proc(pool: ^Pool, task: Task) {
  258. {
  259. context.allocator = task.allocator
  260. task.procedure(task)
  261. }
  262. sync.guard(&pool.mutex)
  263. append(&pool.tasks_done, task)
  264. intrinsics.atomic_add(&pool.num_done, 1)
  265. intrinsics.atomic_sub(&pool.num_outstanding, 1)
  266. intrinsics.atomic_sub(&pool.num_in_processing, 1)
  267. }
  268. // Process the rest of the tasks, also use this thread for processing, then join
  269. // all the pool threads.
  270. pool_finish :: proc(pool: ^Pool) {
  271. for task in pool_pop_waiting(pool) {
  272. pool_do_work(pool, task)
  273. }
  274. pool_join(pool)
  275. }