From 5d9d262a26589107f7dd2fc615464cebf08061aa Mon Sep 17 00:00:00 2001 From: Jian Han Date: Wed, 9 May 2018 21:07:57 +1000 Subject: [PATCH] example for david with sem + iterator --- concurrency/iterator_sem/main.go | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 concurrency/iterator_sem/main.go diff --git a/concurrency/iterator_sem/main.go b/concurrency/iterator_sem/main.go new file mode 100644 index 0000000..ed7f40c --- /dev/null +++ b/concurrency/iterator_sem/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "math/rand" + "sync" + "time" +) + +func main() { + + generator := func() <-chan int { + totalIteration := 30 + wg := &sync.WaitGroup{} + wg.Add(totalIteration) + concurrentCount := 20 + sem := make(chan bool, concurrentCount) + defer close(sem) + results := make(chan int, totalIteration) + defer close(results) + for i := 0; i < totalIteration; i++ { + sem <- true + go func(i int) { + results <- generateNumber() + <-sem + wg.Done() + }(i) + } + wg.Wait() + return results + } + + results := generator() + for r := range results { + fmt.Println(r) + } + + fmt.Println("Finished!!!") +} + +func generateNumber() int { + rand.Seed(time.Now().Unix()) + time.Sleep(time.Second) + return rand.Intn(10000) +}