thread.odin 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. _ :: compile_assert(ODIN_OS == "windows");
  2. when ODIN_OS == "windows" {
  3. import win32 "core:sys/windows.odin"
  4. }
  5. Thread_Proc :: #type proc(^Thread) -> int;
  6. Thread_Os_Specific :: struct {
  7. win32_thread: win32.Handle,
  8. win32_thread_id: u32,
  9. }
  10. Thread :: struct {
  11. using specific: Thread_Os_Specific,
  12. procedure: Thread_Proc,
  13. data: rawptr,
  14. user_index: int,
  15. init_context: Context,
  16. use_init_context: bool,
  17. }
  18. create :: proc(procedure: Thread_Proc) -> ^Thread {
  19. win32_thread_id: u32;
  20. __windows_thread_entry_proc :: proc "c" (t: ^Thread) -> i32 {
  21. c := context;
  22. if t.use_init_context {
  23. c = t.init_context;
  24. }
  25. exit := 0;
  26. context <- c {
  27. exit = t.procedure(t);
  28. }
  29. return i32(exit);
  30. }
  31. win32_thread_proc := rawptr(__windows_thread_entry_proc);
  32. thread := new(Thread);
  33. win32_thread := win32.create_thread(nil, 0, win32_thread_proc, thread, win32.CREATE_SUSPENDED, &win32_thread_id);
  34. if win32_thread == nil {
  35. free(thread);
  36. return nil;
  37. }
  38. thread.procedure = procedure;
  39. thread.win32_thread = win32_thread;
  40. thread.win32_thread_id = win32_thread_id;
  41. return thread;
  42. }
  43. start :: proc(using thread: ^Thread) {
  44. win32.resume_thread(win32_thread);
  45. }
  46. is_done :: proc(using thread: ^Thread) -> bool {
  47. res := win32.wait_for_single_object(win32_thread, 0);
  48. return res != win32.WAIT_TIMEOUT;
  49. }
  50. join :: proc(using thread: ^Thread) {
  51. win32.wait_for_single_object(win32_thread, win32.INFINITE);
  52. win32.close_handle(win32_thread);
  53. win32_thread = win32.INVALID_HANDLE;
  54. }
  55. destroy :: proc(thread: ^Thread) {
  56. join(thread);
  57. free(thread);
  58. }