thread_management.odin 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package runtime
  2. Thread_Local_Cleaner_Odin :: #type proc "odin" ()
  3. Thread_Local_Cleaner_Contextless :: #type proc "contextless" ()
  4. Thread_Local_Cleaner :: union #shared_nil {Thread_Local_Cleaner_Odin, Thread_Local_Cleaner_Contextless}
  5. @(private="file")
  6. thread_local_cleaners: [8]Thread_Local_Cleaner
  7. // Add a procedure that will be run at the end of a thread for the purpose of
  8. // deallocating state marked as `thread_local`.
  9. //
  10. // Intended to be called in an `init` procedure of a package with
  11. // dynamically-allocated memory that is stored in `thread_local` variables.
  12. add_thread_local_cleaner :: proc "contextless" (p: Thread_Local_Cleaner) {
  13. for &v in thread_local_cleaners {
  14. if v == nil {
  15. v = p
  16. return
  17. }
  18. }
  19. panic_contextless("There are no more thread-local cleaner slots available.")
  20. }
  21. // Run all of the thread-local cleaner procedures.
  22. //
  23. // Intended to be called by the internals of a threading API at the end of a
  24. // thread's lifetime.
  25. run_thread_local_cleaners :: proc "odin" () {
  26. for p in thread_local_cleaners {
  27. if p == nil {
  28. break
  29. }
  30. switch v in p {
  31. case Thread_Local_Cleaner_Odin: v()
  32. case Thread_Local_Cleaner_Contextless: v()
  33. }
  34. }
  35. }