thr1.odin 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import "core:fmt"
  3. import "core:thread"
  4. import "core:sync"
  5. myMutex :sync.Mutex
  6. // A structure for the data that we are gonna pass in our multithreaded function
  7. workerData :: struct{
  8. // waitGroup is passed so that when our process is done,
  9. // we can tell our main thread via this
  10. waitgroupdata: ^sync.Wait_Group
  11. }
  12. main :: proc(){
  13. // initilizing a wait group which will keep track of our threads
  14. // it is used to check if our thread has completed its work or not
  15. wg : sync.Wait_Group
  16. // creating a new thread
  17. t1 := thread.create(worker)
  18. t1.init_context = context
  19. t1.user_index = 1
  20. t1.data = &workerData{ waitgroupdata = &wg}
  21. t2 := thread.create(worker)
  22. t2.init_context = context
  23. t2.user_index = 2
  24. t2.data = &workerData{ waitgroupdata = &wg}
  25. // this function takes in counter of how many threads are going to start
  26. // In our case we are just spinning up 2 thread
  27. sync.wait_group_add(&wg, 2)
  28. // starting our thread
  29. thread.start(t1)
  30. thread.start(t2)
  31. /*
  32. waiting for our threads to complete their work
  33. this function checks if our counter value is greater than 0
  34. if counter is greater than 0 then that means our threads are still working
  35. and when it becomes 0 then all threads are done with there work and we can down
  36. Internally it looks something like this
  37. for wg.counter != 0 { }
  38. */
  39. sync.wait_group_wait(&wg)
  40. }
  41. worker :: proc(t: ^thread.Thread){
  42. fmt.printf("work of thread %v started\n", t.user_index)
  43. // getting values that we passed while initilizing our thread
  44. dereferenced_value := (cast(^workerData)t.data)
  45. fmt.printfln("work of thread %v done", t.user_index)
  46. // this function just does counter--
  47. // which tells that our function has done its work
  48. sync.wait_group_done(dereferenced_value.waitgroupdata)
  49. }
  50. /*
  51. make o thr1
  52. odin run thr1.odin -file
  53. work of thread 1 started
  54. work of thread 1 done
  55. work of thread 2 started
  56. work of thread 2 done
  57. */