forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise2.go
51 lines (41 loc) · 1.3 KB
/
exercise2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Write a program that uses a fan out pattern to generate 100 random numbers
// concurrently. Have each goroutine generate a single random number and return
// that number to the main goroutine over a buffered channel. Set the size of
// the buffer channel so no send every blocks. Don't allocate more buffers than
// you need. Have the main goroutine display each random number is receives and
// then terminate the program.
package main
import (
"fmt"
"math/rand"
"time"
)
const (
goroutines = 100
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
// Create the buffer channel with a buffer for
// each goroutine to be created.
values := make(chan int, goroutines)
// Iterate and launch each goroutine.
for gr := 0; gr < goroutines; gr++ {
// Create an anonymous function for each goroutine that
// generates a random number and sends it on the channel.
go func() {
values <- rand.Intn(1000)
}()
}
// Create a variable to be used to track received messages.
// Set the value to the number of goroutines created.
wait := goroutines
// Iterate receiving each value until they are all received.
for wait > 0 {
fmt.Println(wait, <-values)
wait--
}
}