ch9/ch9-08 #191
ch9/ch9-08
#191
Replies: 5 comments 2 replies
-
9.4 不太懂但是内存确实占用了 func liu(a chan int) {
for {
i := <-a
fmt.Println(i + 1)
b := make(chan int)
go liu(b)
b <- i + 1
}
}
func main() {
a := make(chan int)
// b := make(chan int)
go liu(a)
a <- 1
for {
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
9.5 func pingPong(in chan int, out chan int) {
for {
count := <-in
out <- count + 1
}
}
func main() {
ping := make(chan int)
pong := make(chan int)
go pingPong(ping, pong)
go pingPong(pong, ping)
ping <- 0
time.Sleep(1 * time.Second)
counter := <-ping
fmt.Println("counter: ", counter) // 3623866
} |
Beta Was this translation helpful? Give feedback.
1 reply
-
func main() {
done := make(chan bool)
ch1, ch2 := make(chan string), make(chan string)
var count1, count2 int
go func() {
for {
select {
case <-done:
fmt.Println("Goroutine 1 Done")
return
case ch1 <- "ping-pong":
<-ch2
count1++
}
}
}()
go func() {
for {
select {
case <-done:
fmt.Println("Goroutine 2 Done")
return
case <-ch1:
ch2 <- "ping-pong"
count2++
}
}
}()
time.Sleep(1 * time.Second)
close(done)
time.Sleep(100 * time.Millisecond)
fmt.Println(count1 + count2)
} |
Beta Was this translation helpful? Give feedback.
1 reply
-
16GB 内存的M1 芯片的iMac能创建36219000 多个 goroutine。 func main() {
nums := make(chan int)
go func() {
var max int64
for {
max++
if max % 1000 == 0 {
println(max)
}
go func() {
<-nums
}()
}
}()
<-nums
} 输出: ...
36219000
signal: killed |
Beta Was this translation helpful? Give feedback.
0 replies
-
9.5 package main
import (
"fmt"
"time"
)
func main() {
numPi := 0
numPo := 0
pings := make(chan string)
pongs := make(chan string)
tick := time.Tick(1 * time.Second)
go func() {
for {
pings <- "ping"
}
}()
go func() {
for {
pongs <- "pong"
}
}()
loop:
for {
select {
case <- tick:
break loop
case <-pings:
numPi++
case <-pongs:
numPo++
}
}
fmt.Printf("ping: %d, pong: %d\n", numPi, numPo)
} 输出 ping: 1623912, pong: 1745154 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
ch9/ch9-08
中文版
https://gopl-zh.github.io/ch9/ch9-08.html
Beta Was this translation helpful? Give feedback.
All reactions