|
@@ -0,0 +1,92 @@
|
|
|
|
+
|
|
|
|
+package main
|
|
|
|
+
|
|
|
|
+import "core:fmt"
|
|
|
|
+import "core:thread"
|
|
|
|
+import "core:time"
|
|
|
|
+import "core:sync"
|
|
|
|
+import "core:sync/chan"
|
|
|
|
+
|
|
|
|
+my_mutex :sync.Mutex
|
|
|
|
+
|
|
|
|
+wData :: struct{
|
|
|
|
+ waitgroupdata: ^sync.Wait_Group,
|
|
|
|
+ // message_channel is like a cannal/converbelt
|
|
|
|
+ // through which we can pass things
|
|
|
|
+ message_channel: ^chan.Chan(int)
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+main :: proc(){
|
|
|
|
+ wg : sync.Wait_Group
|
|
|
|
+ // creating a new channel which can pass int type data
|
|
|
|
+ mchan, err := chan.create(chan.Chan(int), context.allocator)
|
|
|
|
+
|
|
|
|
+ t1 := thread.create(worker1)
|
|
|
|
+ t2 := thread.create(worker2)
|
|
|
|
+
|
|
|
|
+ t1.init_context = context
|
|
|
|
+ t1.user_index = 1
|
|
|
|
+
|
|
|
|
+ t2.init_context = context
|
|
|
|
+ t2.user_index = 2
|
|
|
|
+
|
|
|
|
+ t1.data = &wData{ waitgroupdata = &wg, message_channel = &mchan }
|
|
|
|
+ t2.data = &wData{ waitgroupdata = &wg, message_channel = &mchan }
|
|
|
|
+
|
|
|
|
+ sync.wait_group_add(&wg, 2)
|
|
|
|
+ thread.start(t1)
|
|
|
|
+ thread.start(t2)
|
|
|
|
+ sync.wait_group_wait(&wg)
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+worker1 :: proc(t: ^thread.Thread){
|
|
|
|
+ fmt.printf("work of t1 started\n")
|
|
|
|
+ dereferenced_value := (cast(^wData)t.data)
|
|
|
|
+
|
|
|
|
+ // passing 24 through our channel
|
|
|
|
+ // now this 24 can be picked up by other threads using this channel
|
|
|
|
+ ok := chan.send(dereferenced_value.message_channel^, 24)
|
|
|
|
+ if ok{
|
|
|
|
+ fmt.println("t1 sent message via chan")
|
|
|
|
+ }else{
|
|
|
|
+ fmt.println("couldn't send message")
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ sync.wait_group_done(dereferenced_value.waitgroupdata)
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+worker2 :: proc (t: ^thread.Thread){
|
|
|
|
+ fmt.printf("work of t2 started \n")
|
|
|
|
+ dereferenced_value := (cast(^wData)t.data)
|
|
|
|
+
|
|
|
|
+ // This will wait here till we recieve any data through channel
|
|
|
|
+ // once we get data from channel we can move forward
|
|
|
|
+ data, ok := chan.recv(dereferenced_value.message_channel^)
|
|
|
|
+ if ok{
|
|
|
|
+ fmt.printf("Recieved %d from t1\n", data)
|
|
|
|
+ }else{
|
|
|
|
+ fmt.printf("Something went wrong\n")
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ sync.wait_group_done(dereferenced_value.waitgroupdata)
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+/*
|
|
|
|
+
|
|
|
|
+make o thr4
|
|
|
|
+odin run thr4.odin -file
|
|
|
|
+work of t1 started
|
|
|
|
+work of t2 started
|
|
|
|
+Recieved 24 from t1
|
|
|
|
+t1 sent message via chan
|
|
|
|
+
|
|
|
|
+make o thr4
|
|
|
|
+odin run thr4.odin -file
|
|
|
|
+work of t2 started
|
|
|
|
+work of t1 started
|
|
|
|
+Recieved 24 from t1
|
|
|
|
+t1 sent message via chan
|
|
|
|
+
|
|
|
|
+*/
|
|
|
|
+
|