Browse Source

threads 2 example

221V 2 weeks ago
parent
commit
9e2891a156
1 changed files with 73 additions and 0 deletions
  1. 73 0
      otest/thr2.odin

+ 73 - 0
otest/thr2.odin

@@ -0,0 +1,73 @@
+
+package main
+
+import "core:fmt"
+import "core:thread"
+import "core:time"
+
+arr := []int{1,2,3}
+main :: proc(){
+  // creating a dynamic array of len of array which stores pointer to a thread
+  threadPool := make([dynamic]^thread.Thread, 0, len(arr))
+  defer delete(threadPool)
+  
+  for i in 0..<len(arr){
+    thr := thread.create(worker) // creating a thread
+    if thr != nil{
+      // setting up context for our thread
+      thr.init_context = context
+      // giving our thread id
+      thr.user_index = i 
+      // Adding our thread to thread pool
+      append(&threadPool, thr) 
+      
+      thread.start(thr) // running our thread
+    }
+  }
+  
+  // looping till all of our threads have done their work
+  // i.e till our threadPool is empty
+  // our threadPool becomes empty because after each 
+  for len(threadPool) > 0{
+    for i := 0; i < len(threadPool); {
+      // Getting a threads address at index i
+      t := threadPool[i]
+      if thread.is_done(t){
+        fmt.printf("Thread %d is done\n", arr[t.user_index])
+        thread.destroy(t)
+        // removing address of destroyed thread from out pool
+        ordered_remove(&threadPool, i)
+      }else{
+        // If current thread process is not done then go to next one
+        i += 1 
+      }
+    }
+  }
+}
+
+worker :: proc(t: ^thread.Thread){
+  // with the help of context we get what thread we are using.
+  fmt.printf("work of t%d\n", arr[t.user_index])
+}
+
+
+/*
+
+odin run thr2.odin -file
+work of t1
+Thread 1 is done
+work of t3
+Thread 3 is done
+work of t2
+Thread 2 is done
+
+odin run thr2.odin -file
+work of t1
+Thread 1 is done
+work of t3
+work of t2
+Thread 3 is done
+Thread 2 is done
+
+*/
+