thr4.odin 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package main
  2. import "core:fmt"
  3. import "core:thread"
  4. import "core:time"
  5. import "core:sync"
  6. import "core:sync/chan"
  7. my_mutex :sync.Mutex
  8. wData :: struct{
  9. waitgroupdata: ^sync.Wait_Group,
  10. // message_channel is like a cannal/converbelt
  11. // through which we can pass things
  12. message_channel: ^chan.Chan(int)
  13. }
  14. main :: proc(){
  15. wg : sync.Wait_Group
  16. // creating a new channel which can pass int type data
  17. mchan, err := chan.create(chan.Chan(int), context.allocator)
  18. t1 := thread.create(worker1)
  19. t2 := thread.create(worker2)
  20. t1.init_context = context
  21. t1.user_index = 1
  22. t2.init_context = context
  23. t2.user_index = 2
  24. t1.data = &wData{ waitgroupdata = &wg, message_channel = &mchan }
  25. t2.data = &wData{ waitgroupdata = &wg, message_channel = &mchan }
  26. sync.wait_group_add(&wg, 2)
  27. thread.start(t1)
  28. thread.start(t2)
  29. sync.wait_group_wait(&wg)
  30. }
  31. worker1 :: proc(t: ^thread.Thread){
  32. fmt.printf("work of t1 started\n")
  33. dereferenced_value := (cast(^wData)t.data)
  34. // passing 24 through our channel
  35. // now this 24 can be picked up by other threads using this channel
  36. ok := chan.send(dereferenced_value.message_channel^, 24)
  37. if ok{
  38. fmt.println("t1 sent message via chan")
  39. }else{
  40. fmt.println("couldn't send message")
  41. }
  42. sync.wait_group_done(dereferenced_value.waitgroupdata)
  43. }
  44. worker2 :: proc (t: ^thread.Thread){
  45. fmt.printf("work of t2 started \n")
  46. dereferenced_value := (cast(^wData)t.data)
  47. // This will wait here till we recieve any data through channel
  48. // once we get data from channel we can move forward
  49. data, ok := chan.recv(dereferenced_value.message_channel^)
  50. if ok{
  51. fmt.printf("Recieved %d from t1\n", data)
  52. }else{
  53. fmt.printf("Something went wrong\n")
  54. }
  55. sync.wait_group_done(dereferenced_value.waitgroupdata)
  56. }
  57. /*
  58. make o thr4
  59. odin run thr4.odin -file
  60. work of t1 started
  61. work of t2 started
  62. Recieved 24 from t1
  63. t1 sent message via chan
  64. make o thr4
  65. odin run thr4.odin -file
  66. work of t2 started
  67. work of t1 started
  68. Recieved 24 from t1
  69. t1 sent message via chan
  70. */