Compare commits
2 Commits
bea0d5c00e
...
cb314c36a9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cb314c36a9 | ||
|
|
e66d76ddc9 |
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
*.exe
|
||||
39
ch12/1/ch12_1.go
Normal file
39
ch12/1/ch12_1.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
)
|
||||
|
||||
func PrintNumbers() {
|
||||
const IN_CHAN_NUM = 2
|
||||
numCh := make(chan int, 20)
|
||||
completeCh := make(chan int)
|
||||
defer close(numCh)
|
||||
defer close(completeCh)
|
||||
for i := 0; i < IN_CHAN_NUM; i++ {
|
||||
go func() {
|
||||
for j := 0; j < 10; j++ {
|
||||
numCh <- (rand.Int() % 100)
|
||||
}
|
||||
}()
|
||||
}
|
||||
go func() {
|
||||
i := 0
|
||||
for num := range numCh {
|
||||
fmt.Println(num)
|
||||
i++
|
||||
if i == 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
completeCh <- 1
|
||||
}()
|
||||
select {
|
||||
case <-completeCh:
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
PrintNumbers()
|
||||
}
|
||||
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()
|
||||
}
|
||||
3
ch12/2/go.mod
Normal file
3
ch12/2/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module gitea.local.lab/Lbenedar/learning_go/ch12/2
|
||||
|
||||
go 1.25.0
|
||||
Reference in New Issue
Block a user