Skip to content

Commit 9f900d1

Browse files
committed
adding documentation around goroutines
1 parent 300cfbe commit 9f900d1

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ all the examples `Run` functions sequentially in line with the table of contents
3535
* [21 - Struct Embedding](structembedding/main.go)
3636
* [22 - Generics](generics/main.go)
3737
* [23 - Errors](errors/main.go)
38+
* [24 - Goroutines](goroutines/main.go)
3839
* [34 - Timers](timers/main.go)
3940
* [35 - Tickers](tickers/main.go)
4041
* [36 - Worker Pools](workerpools/main.go)

goroutines/main.go

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
}

main.go

+2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/symonk/learning-golang/forloop"
1212
"github.com/symonk/learning-golang/functions"
1313
"github.com/symonk/learning-golang/generics"
14+
"github.com/symonk/learning-golang/goroutines"
1415
"github.com/symonk/learning-golang/helloworld"
1516
"github.com/symonk/learning-golang/ifelse"
1617
"github.com/symonk/learning-golang/interfaces"
@@ -82,5 +83,6 @@ func buildMap() map[string]func() {
8283
fnMap["structembedding"] = structembedding.Run
8384
fnMap["generics"] = generics.Run
8485
fnMap["errors"] = errors.Run
86+
fnMap["goroutines"] = goroutines.Run
8587
return fnMap
8688
}

0 commit comments

Comments
 (0)