add ch12_2
This commit is contained in:
44
ch12/2/ch12_2.go
Normal file
44
ch12/2/ch12_2.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
func PrintNumbers() {
|
||||
const chNum = 2
|
||||
firstCh := make(chan int, 10)
|
||||
secondCh := make(chan int, 20)
|
||||
defer close(firstCh)
|
||||
defer close(secondCh)
|
||||
|
||||
go func() {
|
||||
for j := 0; j < 10; j++ {
|
||||
firstCh <- (rand.Int() % 100)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
for j := 0; j < 10; j++ {
|
||||
secondCh <- (rand.Int() % 100)
|
||||
}
|
||||
}()
|
||||
|
||||
i := 0
|
||||
forLoop:
|
||||
for {
|
||||
select {
|
||||
case val1 := <-firstCh:
|
||||
fmt.Printf("(%d) From first channel: %d\n", i+1, val1)
|
||||
case val2 := <-secondCh:
|
||||
fmt.Printf("(%d) From second channel: %d\n", i+1, val2)
|
||||
}
|
||||
i++
|
||||
if i == chNum*10 {
|
||||
break forLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
PrintNumbers()
|
||||
}
|
||||
Reference in New Issue
Block a user