-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathconcurrency.go
118 lines (97 loc) · 2.14 KB
/
concurrency.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// Copyright (c) Efficient Go Authors
// Licensed under the Apache License 2.0.
package concurrency
import (
"math/rand"
"sync"
"sync/atomic"
)
// Simplest example of goroutines.
// Read more in "Efficient Go"; Example 4-5.
func anotherFunction(arg1 string) { /*...*/ }
func function() {
// Scope of the current goroutine.
// ...
go func() {
// This scope will run concurrently any moment now.
// ...
}()
// anotherFunction will run concurrently any moment now.
go anotherFunction("argument1")
// After our function ends, two goroutines we started can still run.
return
}
var randInt64 = func() int64 {
return rand.Int63()
}
// Example of communicating state between goroutines using atomic operations.
// Read more in "Efficient Go"; Example 4-6.
func sharingWithAtomic() (sum int64) {
var wg sync.WaitGroup
concurrentFn := func() {
// ...
atomic.AddInt64(&sum, randInt64())
wg.Done()
}
wg.Add(3)
go concurrentFn()
go concurrentFn()
go concurrentFn()
wg.Wait()
return sum
}
// Example of communicating state between goroutines using mutex locking.
// Read more in "Efficient Go"; Example 4-7.
func sharingWithMutex() (sum int64) {
var wg sync.WaitGroup
var mu sync.Mutex
concurrentFn := func() {
// ...
mu.Lock()
sum += randInt64()
mu.Unlock()
wg.Done()
}
wg.Add(3)
go concurrentFn()
go concurrentFn()
go concurrentFn()
wg.Wait()
return sum
}
// Example of communicating state between goroutines using mutex locking.
// Read more in "Efficient Go"; Example 4-8.
func sharingWithChannel() (sum int64) {
result := make(chan int64)
concurrentFn := func() {
// ...
result <- randInt64()
}
go concurrentFn()
go concurrentFn()
go concurrentFn()
for i := 0; i < 3; i++ {
sum += <-result
}
close(result)
return sum
}
// Example of communicating state between goroutines using sharded space.
func sharingWithShardedSpace() (sum int64) {
var wg sync.WaitGroup
results := [3]int64{}
concurrentFn := func(i int) {
// ...
results[i] = randInt64()
wg.Done()
}
wg.Add(3)
go concurrentFn(0)
go concurrentFn(1)
go concurrentFn(2)
wg.Wait()
for _, res := range results {
sum += res
}
return sum
}