浅谈go 的select

因为go的channel是并发执行的,并不像swoole的chan,这时候就会产生一个问题,如果我有两个或者更多的chan,我怎么先执行执行速度更快的哪一个,或者到一定的时间我要终止他,等等,select可以解决
package main

import (
    "fmt"
    "time"
)

//
func everyUse() chan int {
    output := make(chan int)
    for i := 0; i < 2000; i++ {
        go func(i int) {
            for {
                time.Sleep(time.Second)
                output <- i
            }
        }(i)
    }

    return output
}

//use create
func createworker(id int) chan int {
    c := make(chan int)
    go func() {
        for {
            fmt.Printf("is %d,come %d\n", id, <-c)
        }
    }()
    return c
}

func main() {
    var c1, c2 = everyUse(), everyUse() //make double channel
    var values []int                    //create a quene
    var worker = createworker(0)        //var worker
    //run 10s to stop
    tm := time.After(10 * time.Second)
    //1s i can see values len
    tk := time.Tick(time.Second)
    for { // if no tm it will work never stop
        var activeWork chan int //make channel
        var activeValue int     //make value
        if len(values) > 0 {    //if has values
            activeWork = worker
            activeValue = values[0] //activeValue is now your value
        }

        select {
        case n := <-c1:
            values = append(values, n) //input queue
        case n := <-c2:
            values = append(values, n) //input queue
        case activeWork <- activeValue: //make your now value goto channel to worker to createrWorker
            values = values[1:]
        case <-time.After(800 * time.Microsecond): //if 800ms no value echo timeout
            fmt.Println("time out")
        case <-tk: //1s i see may values len
            fmt.Printf("values  len is %d", len(values))
        case <-tm: //good bye
            fmt.Println("see you na la")
            return
        }
    }

}


select 不会就某一个case一直读取,会读取当前可以读取到的case,当没有读取到case的时候,就会执行default,有数据读取到额时候就会执行case

vscode不支持中文注释,会警告,强迫症,中文式英语……

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容