-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (41 loc) · 882 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package goroutines
import (
"fmt"
"sync"
"time"
)
/*
A `goroutine` is a lightweight thread of execution.
Waitgroups are outlined in depth in the `WaitGroups` module
but here includes a small taster for them aswell.
*/
func Run() {
synchroniseExample()
asynchronousExample()
waitForManyGoroutines()
}
func Goro(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
// Important to note: This is non blocking and will *not* wait for Goro to finish before exiting.
func asynchronousExample() {
go Goro("Hello")
}
func synchroniseExample() {
Goro("foo")
}
func waitForManyGoroutines() {
var wg sync.WaitGroup
amount := 100
wg.Add(amount)
for i := 0; i < amount; i++ {
go func() {
time.Sleep(1 * time.Second)
wg.Done()
}()
}
wg.Wait() // Wait for all goroutines to finish
fmt.Printf("Waited for %d goroutines to complete\n", amount)
}