mirror of
https://github.com/wahyd4/oz-lotto.git
synced 2026-08-08 21:07:36 +10:00
add goroutine
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user