码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-12-03 12:46:38      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:case   code   匿名   状态   make   匿名函数   读取   超时   pack   

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

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

标签:case   code   匿名   状态   make   匿名函数   读取   超时   pack   

原文地址:http://blog.51cto.com/huwho/2325229

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!