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語句
99 次點擊