1. 程式人生 > >golang中select實現非阻塞及超時控制

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!")
}