thread.odin 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. _ :: compile_assert(ODIN_OS == "windows");
  2. import win32 "sys/windows.odin";
  3. Thread :: struct {
  4. using specific: OsSpecific;
  5. procedure: Proc;
  6. data: any;
  7. user_index: int;
  8. init_context: Context;
  9. use_init_context: bool;
  10. Proc :: #type proc(^Thread) -> int;
  11. OsSpecific :: struct {
  12. win32_thread: win32.Handle;
  13. win32_thread_id: u32;
  14. }
  15. }
  16. create :: proc(procedure: Thread.Proc) -> ^Thread {
  17. win32_thread_id: u32;
  18. __windows_thread_entry_proc :: proc(data: rawptr) -> i32 #cc_c {
  19. if data == nil do return 0;
  20. t := cast(^Thread)data;
  21. c := context;
  22. if t.use_init_context {
  23. c = t.init_context;
  24. }
  25. exit := 0;
  26. push_context c {
  27. exit = t.procedure(t);
  28. }
  29. return cast(i32)exit;
  30. }
  31. win32_thread_proc := cast(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. }