1.for循环里被关闭的通道
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go func() {
time.Sleep(time.Second)
c <- 10
close(c)
}()
for {
select {
case x, ok := <-c:
fmt.Println(x, ok)
time.Sleep(500 * time.Millisecond)
default:
fmt.Println("xxx")
time.Sleep(500 * time.Millisecond)
}
}
}
xxx
xxx
10 true
0 false
0 false
0 false
0 false
2.怎么样才能不读关闭后通道
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go func() {
time.Sleep(time.Second)
c <- 10
close(c)
}()
for {
select {
case x, ok := <-c:
fmt.Println(x, ok)
time.Sleep(500 * time.Millisecond)
if !ok {
c = nil
}
default:
fmt.Println("xxx")
time.Sleep(500 * time.Millisecond)
}
}
}
3.如果select里只有一个已经关闭的case,会怎么样?
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go func() {
time.Sleep(time.Second)
c <- 10
close(c)
}()
for {
select {
case x, ok := <-c:
fmt.Println(x, ok)
time.Sleep(500 * time.Millisecond)
}
}
}
10 true
0 false
0 false
0 false
0 false
4.select里只有一个已经关闭的case,置为nil,会怎么样?
panic