From d6b1144ac0423b86666510117a6e69bd64ba2970 Mon Sep 17 00:00:00 2001 From: Junwei Zhao Date: Tue, 23 Apr 2019 15:52:42 +1000 Subject: [PATCH] add goroutine --- main.go | 48 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 13 deletions(-) diff --git a/main.go b/main.go index 3eb442d..5a4e336 100644 --- a/main.go +++ b/main.go @@ -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