221V 3 недель назад
Родитель
Сommit
3909cbc497
1 измененных файлов с 72 добавлено и 0 удалено
  1. 72 0
      otest/thr1.odin

+ 72 - 0
otest/thr1.odin

@@ -0,0 +1,72 @@
+
+package main
+
+import "core:fmt"
+import "core:thread"
+import "core:sync"
+
+myMutex :sync.Mutex
+
+// A structure for the data that we are gonna pass in our multithreaded function
+workerData :: struct{
+  // waitGroup is passed so that when our process is done,
+  // we can tell our main thread via this
+  waitgroupdata: ^sync.Wait_Group
+}
+
+main :: proc(){
+  // initilizing a wait group which will keep track of our threads
+  // it is used to check if our thread has completed its work or not
+  wg : sync.Wait_Group
+  
+  // creating a new thread
+  t1 := thread.create(worker)
+  t1.init_context = context
+  t1.user_index = 1
+  t1.data = &workerData{ waitgroupdata = &wg}
+  
+  t2 := thread.create(worker)
+  t2.init_context = context
+  t2.user_index = 2
+  t2.data = &workerData{ waitgroupdata = &wg}
+  
+  // this function takes in counter of how many threads are going to start
+  // In our case we are just spinning up 2 thread
+  sync.wait_group_add(&wg, 2)
+  // starting our thread
+  thread.start(t1)
+  thread.start(t2)
+  /*
+  waiting for our threads to complete their work
+  this function checks if our counter value is greater than 0
+  if counter is greater than 0 then that means our threads are still working
+  and when it becomes 0 then all threads are done with there work and we can down
+  
+  Internally it looks something like this
+  for wg.counter != 0 { }
+  */
+  sync.wait_group_wait(&wg)
+}
+
+worker :: proc(t: ^thread.Thread){
+  fmt.printf("work of thread  %v started\n", t.user_index)
+  // getting values that we passed while initilizing our thread
+  dereferenced_value := (cast(^workerData)t.data)
+  fmt.printfln("work of thread %v done", t.user_index)
+  // this function just does counter--
+  // which tells that our function has done its work
+  sync.wait_group_done(dereferenced_value.waitgroupdata)
+}
+
+
+/*
+
+make o thr1
+odin run thr1.odin -file
+work of thread  1 started
+work of thread 1 done
+work of thread  2 started
+work of thread 2 done
+
+*/
+