-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9_SyncPrimitives.go
88 lines (70 loc) · 1.53 KB
/
9_SyncPrimitives.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
/*
- GOMAXPROC > 1
- waitgroup: add[add(-1)], done, wait
- mutex
- GOMAXPROC -> env == go env
- go run/build -race == check race conditions
- 8128 limit of goroutines
- defer for multiple unlocks
- rwMutex == all can read while on write blocks all readers
- sync.Map
- sync.Pool == storage of temporary objects, cache objects, avoid not necessary allocation
- sync.Once == only first call
- sync.Cond == waiting for an event [Broadcast, Signal, Wait]
*/
type Dog struct {
name string
walkDuration time.Duration
}
func (d Dog) Walk(wg *sync.WaitGroup) {
fmt.Printf("%s is taking a walk\n", d.name)
time.Sleep(d.walkDuration)
fmt.Printf("%s is going home\n", d.name)
wg.Done()
}
type httpPkg struct{}
func (httpPkg) Get(url string) {}
var http httpPkg
var i int // i == 0
func worker(wg *sync.WaitGroup, mu *sync.Mutex) {
mu.Lock()
i = i + 1
mu.Unlock()
wg.Done()
}
func main() {
dogs := []Dog{{"vasya", time.Second}, {"john", time.Second * 3}}
runtime.GOMAXPROCS(4)
var wg = &sync.WaitGroup{}
var mu = &sync.Mutex{}
for _, d := range dogs {
wg.Add(1)
go d.Walk(wg)
}
var urls = []string{
"http://www.golang.org/",
"http://www.google.com/",
"http://www.somestupidname.com/",
}
for _, url := range urls {
wg.Add(1)
go func(url string) {
defer wg.Done()
http.Get(url)
}(url)
}
for i := 0; i < 1000; i++ {
wg.Add(1)
go worker(wg, mu)
}
wg.Wait()
fmt.Println("value of i after 1000 operations is", i)
fmt.Println("everybody's home")
}