channel中select的应用及超时处理

2019-07-23  本文已影响0人  七八个星天

一、利用select,实现斐波那契数列

package main

import (
    "fmt"
    "runtime"
)

func fibonacci(ch <-chan int, quit <-chan bool) {
    for {
        select {
        case num := <-ch:
            fmt.Printf("%d ", num)
        case <-quit:
            runtime.Goexit()
        }
    }
}
func main() {
    x, y := 1, 1
    ch := make(chan int)
    quit := make(chan bool)
    go fibonacci(ch, quit)
    for i := 0; i < 100; i++ {
        ch <- x
        x, y = y, x+y
    }
    quit <- true

}

二、利用time.After实现超时处理

package main

import (
    "fmt"
    "runtime"
    "time"
)

func main() {
    ch := make(chan int)
    quit := make(chan bool)
    i := 0
    go func() {
        for {
            i++
            fmt.Printf("第%d次\n", i)
            select {
            case <-time.After(time.Second * 5): //设定5秒超时
                fmt.Println("超时")
                quit <- true
                runtime.Goexit()
            case num := <-ch:
                fmt.Println(num)

            }
        }
    }()
    for i := 0; i < 5; i++ {
        time.Sleep(time.Second*2)
        ch <- i
    }
    <-quit
}

上一篇下一篇

猜你喜欢

热点阅读