-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.go
51 lines (45 loc) · 969 Bytes
/
mutex.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
package sync_patterns
import "sync"
// mutexNoSync demonstrates that the return value can be supplied before all go routines are finished
func mutexNoSync() int {
counter := 0
for i := 0; i < 1000; i++ {
go func() {
counter++
}()
}
return counter
}
// mutexWithWaitGroup demonstrates that even if we wait for all go routines, a race condition can occur
func mutexWithWaitGroup() int {
n := 1000
counter := 0
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
counter++
}()
}
wg.Wait()
return counter
}
// mutexSolution demonstrates a solution using mutex (atomic operation), which ensure that only one goroutine invokes the operation at time
func mutexSolution() int {
n := 1000
counter := 0
var wg sync.WaitGroup
var mutex sync.Mutex
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
defer mutex.Unlock()
mutex.Lock()
counter++
}()
}
wg.Wait()
return counter
}