温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

golang中select实现非阻塞及超时控制

发布时间:2020-08-05 20:22:06 来源:网络 阅读:2732 作者:PowerMichael 栏目:编程语言
// 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!")
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI