golang中select實現非阻塞及超時控制

// select.go
package main

import (
    "fmt"
    "time"

    //"time"
)

func main() {
    //聲明一個channel
    ch := make(chan int)

    //聲明一個匿名函數,傳入一個參數整型channel類型ch
    go func(ch chan int) {
        ch <- 1
        //往channel寫入一個數據,此時阻塞
    }(ch)

    //由於goroutine執行太快,先讓它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一直處於讀取狀態,所以處於阻塞,使用select實現超時控制
package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int)
    //buffer channel,1個元素前非阻塞
    timeout := make(chan int, 1)

    go func() {
        time.Sleep(time.Second)
        //寫channel
        timeout <- 1
    }()

    select {
    //讀channel
    case <-ch:
        fmt.Print("come to read ch!")
        //沒有讀到channel,實現超時控制
    case <-timeout:
        fmt.Print("come to timeout!")
    }

    fmt.Print("end of code!")
}

// select.go
//使用time.After實現超時控制
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!")
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章