File tree 3 files changed +49
-0
lines changed
3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -35,6 +35,7 @@ all the examples `Run` functions sequentially in line with the table of contents
35
35
* [ 21 - Struct Embedding] ( structembedding/main.go )
36
36
* [ 22 - Generics] ( generics/main.go )
37
37
* [ 23 - Errors] ( errors/main.go )
38
+ * [ 24 - Goroutines] ( goroutines/main.go )
38
39
* [ 34 - Timers] ( timers/main.go )
39
40
* [ 35 - Tickers] ( tickers/main.go )
40
41
* [ 36 - Worker Pools] ( workerpools/main.go )
Original file line number Diff line number Diff line change
1
+ package goroutines
2
+
3
+ import (
4
+ "fmt"
5
+ "sync"
6
+ "time"
7
+ )
8
+
9
+ /*
10
+ A `goroutine` is a lightweight thread of execution.
11
+ */
12
+ func Run () {
13
+ synchroniseExample ()
14
+ asynchronousExample ()
15
+ waitForManyGoroutines ()
16
+ }
17
+
18
+ func Goro (from string ) {
19
+ for i := 0 ; i < 3 ; i ++ {
20
+ fmt .Println (from , ":" , i )
21
+ }
22
+ }
23
+
24
+ // Important to note: This is non blocking and will *not* wait for Goro to finish before exiting.
25
+ func asynchronousExample () {
26
+ go Goro ("Hello" )
27
+ }
28
+
29
+ func synchroniseExample () {
30
+ Goro ("foo" )
31
+ }
32
+
33
+ func waitForManyGoroutines () {
34
+ var wg sync.WaitGroup
35
+ amount := 100
36
+ wg .Add (amount )
37
+ for i := 0 ; i < amount ; i ++ {
38
+ go func () {
39
+ time .Sleep (1 * time .Second )
40
+ wg .Done ()
41
+ }()
42
+ }
43
+
44
+ wg .Wait () // Wait for all goroutines to finish
45
+ fmt .Printf ("Waited for %d goroutines to complete\n " , amount )
46
+ }
Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ import (
11
11
"github.com/symonk/learning-golang/forloop"
12
12
"github.com/symonk/learning-golang/functions"
13
13
"github.com/symonk/learning-golang/generics"
14
+ "github.com/symonk/learning-golang/goroutines"
14
15
"github.com/symonk/learning-golang/helloworld"
15
16
"github.com/symonk/learning-golang/ifelse"
16
17
"github.com/symonk/learning-golang/interfaces"
@@ -82,5 +83,6 @@ func buildMap() map[string]func() {
82
83
fnMap ["structembedding" ] = structembedding .Run
83
84
fnMap ["generics" ] = generics .Run
84
85
fnMap ["errors" ] = errors .Run
86
+ fnMap ["goroutines" ] = goroutines .Run
85
87
return fnMap
86
88
}
You can’t perform that action at this time.
0 commit comments