thr2.odin 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. import "core:fmt"
  3. import "core:thread"
  4. import "core:time"
  5. arr := []int{1,2,3}
  6. main :: proc(){
  7. // creating a dynamic array of len of array which stores pointer to a thread
  8. threadPool := make([dynamic]^thread.Thread, 0, len(arr))
  9. defer delete(threadPool)
  10. for i in 0..<len(arr){
  11. thr := thread.create(worker) // creating a thread
  12. if thr != nil{
  13. // setting up context for our thread
  14. thr.init_context = context
  15. // giving our thread id
  16. thr.user_index = i
  17. // Adding our thread to thread pool
  18. append(&threadPool, thr)
  19. thread.start(thr) // running our thread
  20. }
  21. }
  22. // looping till all of our threads have done their work
  23. // i.e till our threadPool is empty
  24. // our threadPool becomes empty because after each
  25. for len(threadPool) > 0{
  26. for i := 0; i < len(threadPool); {
  27. // Getting a threads address at index i
  28. t := threadPool[i]
  29. if thread.is_done(t){
  30. fmt.printf("Thread %d is done\n", arr[t.user_index])
  31. thread.destroy(t)
  32. // removing address of destroyed thread from out pool
  33. ordered_remove(&threadPool, i)
  34. }else{
  35. // If current thread process is not done then go to next one
  36. i += 1
  37. }
  38. }
  39. }
  40. }
  41. worker :: proc(t: ^thread.Thread){
  42. // with the help of context we get what thread we are using.
  43. fmt.printf("work of t%d\n", arr[t.user_index])
  44. }
  45. /*
  46. odin run thr2.odin -file
  47. work of t1
  48. Thread 1 is done
  49. work of t3
  50. Thread 3 is done
  51. work of t2
  52. Thread 2 is done
  53. odin run thr2.odin -file
  54. work of t1
  55. Thread 1 is done
  56. work of t3
  57. work of t2
  58. Thread 3 is done
  59. Thread 2 is done
  60. */