forked from hoanhan101/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_race_2.go
53 lines (43 loc) · 1.29 KB
/
data_race_2.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
// ----------------
// Atomic Functions
// ----------------
package main
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
)
// counter is a variable incremented by all Goroutines.
// Notice that it's not just an int but int64. We are being very specific about the precision
// because the atomic function requires us to do so.
var counter int64
func main() {
// Number of Goroutines to use.
const grs = 2
// wg is used to manage concurrency.
var wg sync.WaitGroup
wg.Add(grs)
// Create two goroutines.
for i := 0; i < grs; i++ {
go func() {
for count := 0; count < 2; count++ {
// Safely add one to counter.
// Add the atomic functions that we have take an address as the first parameter and
// that is being synchronized, no matter many Goroutines they are. If we call one
// of these function on the same location, they will get serialized. This is the
// fastest way to serialization.
// We can run this program all day long and still get 4 every time.
atomic.AddInt64(&counter, 1)
// This call is now irrelevant because by the time AddInt64 function complete,
// counter is incremented.
runtime.Gosched()
}
wg.Done()
}()
}
// Wait for the Goroutines to finish.
wg.Wait()
// Display the final value.
fmt.Println("Final Counter:", counter)
}