Last active
August 29, 2015 14:07
-
-
Save Barbery/08973672e132d5edfe44 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"runtime" | |
"sync" | |
"sync/atomic" | |
) | |
// var l = &sync.Mutex{} | |
var wait sync.WaitGroup | |
var intNum = 0 | |
var atomicIntNum int32 = 0 | |
var mapNum = make(map[string]int) | |
var sliNum []int | |
func main() { | |
runtime.GOMAXPROCS(runtime.NumCPU()) | |
max := 10 | |
sliNum = append(sliNum, 0) | |
for i := 0; i < 1000; i++ { | |
test(max) | |
} | |
} | |
func initVars() { | |
intNum = 0 | |
atomicIntNum = 0 | |
mapNum["count"] = 0 | |
sliNum[0] = 0 | |
} | |
func test(max int) { | |
initVars() | |
wait.Add(max * 3) | |
for i := 0; i < max; i++ { | |
go add() | |
go add2(mapNum) | |
go add3(sliNum) | |
} | |
wait.Wait() | |
if intNum != 100 || atomicIntNum != 100 || mapNum["count"] != 100 || sliNum[0] != 100 { | |
fmt.Println("intNum", intNum) | |
fmt.Println("atomicIntNum", atomicIntNum) | |
fmt.Println("mapNum", mapNum) | |
fmt.Println("sliNum", sliNum) | |
fmt.Println("------------------------") | |
} | |
} | |
func add() { | |
defer wait.Done() | |
for i := 0; i < 10; i++ { | |
intNum++ | |
atomic.AddInt32(&atomicIntNum, 1) | |
} | |
} | |
func add2(data map[string]int) { | |
defer wait.Done() | |
for i := 0; i < 10; i++ { | |
// l.Lock() | |
data["count"]++ | |
// l.Unlock() | |
} | |
} | |
func add3(data []int) { | |
defer wait.Done() | |
for i := 0; i < 10; i++ { | |
// l.Lock() | |
data[0]++ | |
// l.Unlock() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
intNum 100
atomicIntNum 100
mapNum map[count:93]
sliNum [100]
intNum 93
atomicIntNum 100
mapNum map[count:71]
sliNum [90]
intNum 95
atomicIntNum 100
mapNum map[count:76]
sliNum [100]
intNum 100
atomicIntNum 100
mapNum map[count:83]
sliNum [100]