因为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不支持中文注释,会警告,强迫症,中文式英语……