thread/basics
Code
thread_basics.odin ¶62 linesSource
1/*
2Shows how to start a thread and let it do some calculations while the main
3thead also does some calculations.
4*/
5
6package basic_thread_example
7
8import "core:thread"
9import "core:fmt"
10
11Thread_Data :: struct {
12 // thread input:
13 num_integers_to_sum: int,
14
15 // thread output (don't touch until thread is done!):
16 sum: int,
17}
18
19thread_proc :: proc(t: ^thread.Thread) {
20 fmt.println("Thread starting")
21 d := (^Thread_Data)(t.data)
22
23 for i in 0..<d.num_integers_to_sum {
24 d.sum += i
25 }
26
27 fmt.println("Thread finishing")
28}
29
30main :: proc() {
31 NUM_INTEGERS_TO_SUM :: 10000000
32
33 d := Thread_Data {
34 num_integers_to_sum = NUM_INTEGERS_TO_SUM,
35 }
36
37 t := thread.create(thread_proc)
38 assert(t != nil)
39 t.data = &d
40
41 // Exactly when `thread_proc` starts running isn't certain. The operating
42 // system will schedule it to start soon.
43 thread.start(t)
44
45 fmt.println("Main thread will do the same thing as the other thread, to make sure it does it correctly!")
46
47 sum: int
48 for i in 0..<NUM_INTEGERS_TO_SUM {
49 sum += i
50 }
51
52 fmt.println("OK. Let's wait for the other thread to finish...")
53
54 // thread.join waits for thread to finish. It will block until it is done.
55 thread.join(t)
56 thread.destroy(t)
57
58 // Thread is finished, `d.sum` is safe to read.
59
60 fmt.printfln("Main thread calculated this sum: %v", sum)
61 fmt.printfln("The other thread calculated this sum: %v", d.sum)
62}