// select.go
package main
import (
"fmt"
"time"
//"time"
)
func main() {
//聲明一個(gè)channel
ch := make(chan int)
//聲明一個(gè)匿名函數(shù),傳入一個(gè)參數(shù)整型channel類型ch
go func(ch chan int) {
ch <- 1
//往channel寫入一個(gè)數(shù)據(jù),此時(shí)阻塞
}(ch)
//由于goroutine執(zhí)行太快,先讓它sleep 1秒
time.Sleep(time.Second)
select {
//讀取ch,解除阻塞
case <-ch:
fmt.Print("come to read ch!")
default:
fmt.Print("come to default!")
}
}
// select.go
//整型channel類型ch一直處于讀取狀態(tài),所以處于阻塞,使用select實(shí)現(xiàn)超時(shí)控制
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
//buffer channel,1個(gè)元素前非阻塞
timeout := make(chan int, 1)
go func() {
time.Sleep(time.Second)
//寫channel
timeout <- 1
}()
select {
//讀channel
case <-ch:
fmt.Print("come to read ch!")
//沒(méi)有讀到channel,實(shí)現(xiàn)超時(shí)控制
case <-timeout:
fmt.Print("come to timeout!")
}
fmt.Print("end of code!")
}
// select.go
//使用time.After實(shí)現(xiàn)超時(shí)控制
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
select {
case <-ch:
fmt.Print("come to read ch!")
case <-time.After(time.Second):
fmt.Print("come to timeout!")
}
fmt.Print("end of code!")
}
網(wǎng)站題目:golang中select實(shí)現(xiàn)非阻塞及超時(shí)控制
鏈接地址:
http://weahome.cn/article/pcosjh.html