123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- package main
- import "core:fmt"
- import "core:thread"
- import "core:time"
- import "core:sync"
- myMutex :sync.Mutex
- 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\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])
- }
- */
- worker :: proc(t: ^thread.Thread){
- /*
- when we come to this line
- it will check if myMutex is available or not
- if it isn't then it will wait for it
- and once its available then it will pass and run below code
- */
- //sync.lock(myMutex) // locking before we do our opeartion
- sync.mutex_lock(&myMutex) // locking before we do our opeartion
-
- fmt.printf("work of t%d started\n", arr[t.user_index])
- time.sleep(time.Second)
- fmt.printf("work of t%d completed\n", arr[t.user_index])
- //fmt.println()
-
- //sync.unlock(myMutex) // unlocking for other threads to use it
- sync.mutex_unlock(&myMutex) // unlocking for other threads to use it
- }
- /*
- odin run thr3.odin -file
- work of t1 started
- work of t1 completed
- Thread 1 is done
- work of t2 started
- work of t2 completed
- Thread 2 is done
- work of t3 started
- work of t3 completed
- Thread 3 is done
- odin run thr3.odin -file
- work of t2 started
- work of t2 completed
- Thread 2 is done
- work of t1 started
- work of t1 completed
- Thread 1 is done
- work of t3 started
- work of t3 completed
- Thread 3 is done
- */
|