add goroutine

This commit is contained in:
2019-04-23 15:52:42 +10:00
parent bfa6a3e3ea
commit d6b1144ac0
+35 -13
View File
@@ -4,7 +4,9 @@ import (
"flag"
"fmt"
"math/rand"
"runtime"
"sort"
"sync"
"time"
)
@@ -12,13 +14,16 @@ import (
const (
NumberCount = 7
MaximumResults = 50
Routines = 10
)
var (
winners = make(map[[NumberCount]int]int)
syncWinners sync.Map
signals = make(chan bool, Routines)
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
timesInput := flag.Int("t", 100000, "an int")
flag.Parse()
times := *timesInput
@@ -28,12 +33,27 @@ func main() {
startTime := now.Unix()
fmt.Printf("Started at %v to run lottery for %v times \n", now, times)
for i := 0; i < times; i++ {
winner := run()
if currentTimes, ok := winners[winner]; ok {
winners[winner] = currentTimes + 1
} else {
winners[winner] = 1
for routine := 0; routine < Routines; routine++ {
go func() {
for i := 0; i < times/Routines; i++ {
winner := run()
if currentTimes, ok := syncWinners.Load(winner); ok {
currentTimesInt := currentTimes.(int)
syncWinners.Store(winner, currentTimesInt+1)
} else {
syncWinners.Store(winner, 1)
}
}
signals <- true
}()
}
routineReturnTimes := 0
for range signals {
routineReturnTimes++
fmt.Println(routineReturnTimes)
if routineReturnTimes == Routines {
close(signals)
}
}
@@ -45,13 +65,15 @@ func main() {
}
var ss []kv
for k, v := range winners {
// to reduce the time consuming, if the number only exists once then skip it
if v > 1 {
ss = append(ss, kv{k, v})
}
}
syncWinners.Range(func(key interface{}, value interface{}) bool {
winningTimes := value.(int)
winningNumber := key.([7]int)
if winningTimes > 1 {
ss = append(ss, kv{winningNumber, winningTimes})
}
return true
})
sort.Slice(ss, func(i, j int) bool {
return ss[i].Value > ss[j].Value