Last active
August 1, 2018 07:54
-
-
Save Deleplace/0bfbf70427c1ea84cff5dc8742ca1ae1 to your computer and use it in GitHub Desktop.
The Go race detector catches synchronization bugs only when they actually occur.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
func main() { | |
// Seeding is important for choosing a random counter | |
rand.Seed(time.Now().Unix()) | |
// 3 counters | |
a := []int{0, 0, 0} | |
// 2 tasks will be launched. The main goroutine will | |
// wait for them to complete. | |
var wg sync.WaitGroup | |
wg.Add(2) | |
go func() { | |
i := rand.Intn(3) | |
a[i]++ | |
wg.Done() | |
}() | |
go func() { | |
j := rand.Intn(3) | |
a[j]++ | |
wg.Done() | |
}() | |
wg.Wait() | |
fmt.Println(a) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment