package main
import (
"fmt"
"time"
)
var unbuffered = make(chan struct{}) // 等价于 make(chan struct{},0)
go func(u chan<- struct{}){
for{
select {
case chan<- struct{}{}:
fmt.Println("Written already.")
}
}
}(unbuffered)
go func(u <-chan struct{}){
for{
select {
case <-chan:
fmt.Println("Read already.")
}
}
}(unbuffered)
time.Sleep(time.Second * 5)
结果如下:
Written already.
Read already.
Written already.
Read already.
Read already.
Written already.
Read already.
Written already.
Written already.
Read already.
Read already.
.....
当添加default语句时如下:
go func(u chan<- struct{}){
for{
select {
case chan<- struct{}{}: //unbuffered chan
fmt.Println("Written already.")
default:
fmt.Println("Nothing!")
}
}
}(unbuffered)
go func(u <-chan struct{}){
for{
select {
case <-chan: //unbuffered chan
fmt.Println("Read already.")
default:
fmt.Println("Nothing!")
}
}
}(unbuffered)
运行结果便成了这样样子:
Nothing!
Nothing!
Nothing!
Nothing!
Nothing!
Nothing!
....
执行的一直是default语句
有疑问加站长微信联系(非本文作者)